I set up a proxy in vite.config.ts
:
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import VueDevTools from 'vite-plugin-vue-devtools'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
vueJsx(),
VueDevTools(),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
server: {
proxy: {
'/api': {
target: 'http://localhost:5000',
changeOrigin: true,
rewrite: path => path.replace(/^/api/, ''),
},
},
}
})
This is my app.ts
code looks like:
app.post('/login', async (req, res) => {
try {
const { username, email, password } = req.body;
console.log(username, email, password);
let user = await User.findOne({ $or: [{ username }, { email }] });
if (!user) {
return res.status(400).json({ message: 'User not found' });
}
const isPasswordMatch = await user.comparePassword(password);
if (!isPasswordMatch) {
return res.status(400).json({ message: 'Invalid password' });
}
const userInfo = { id: user._id, username: user.username, email: user.email };
const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET!, { expiresIn: '1h' });
res.cookie('token', token, { httpOnly: true, maxAge: 24 * 60 * 60 * 1000 });
res.status(200).json({ message: 'Login successful', user: userInfo });
} catch (error) {
res.status(500).json({ message: 'Login failed', error });
}
});
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/newpost', upload.array('media'), async (req, res) => {
try {
const { username, caption, price, status, location } = req.body;
const media = (req.files as Express.Multer.File[]).map(file => ({
media: file.buffer.toString('base64')
}));
const newPost = new Post({ username, caption, price, status, location, uploaded: media });
await newPost.save();
res.status(201).json({ message: 'Post created successfully', post: newPost });
} catch (error) {
res.status(500).json({ message: 'Post creation failed', error });
}
});
My axios.post
in this function works fine:
const postNewPost = async () => {
const formData = new FormData();
formData.append('username', 'testuser');
formData.append('caption', caption.value);
formData.append('status', selectedStatus.value);
formData.append('price', price.value?.toString() || '');
formData.append('location', location.value);
selectedMedia.value.forEach((file) => {
formData.append('media', file);
});
try {
const response = await axios.post('/api/newpost', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
alert('Post created successfully!');
emit('post-created');
} catch (error) {
console.error(error);
}
};
But it does not work in this function:
const loginUser = async () => {
const formData = new FormData();
const { value: usernameEmailValue } = usernameEmail;
if (emailRegex.test(usernameEmailValue)) {
formData.append('email', usernameEmailValue);
} else {
formData.append('username', usernameEmailValue);
}
formData.append('password', passwordLogin.value);
try {
const response = await axios.post('/api/login', formData);
if (response.status === 200) {
alert('Login successful');
} else {
alert('Login failed');
}
} catch (error) {
console.error('Login failed:', error);
}
};
when it fails to follow the proxy rule. In console, it says:
POST http://localhost:5173/api/login 500 (Internal Server Error)
Why does this happen even though these functions look almost the same?
1