Why my api is not working as expected? error Invalid request i am testing my api in postman software but its not working its showing me error Invalid request can anyone tell whats the problem?
Backend:
router.post('/save', (req, res) => {
if (!req.user || !req.user.email || !req.body || !req.body.city) {
return res.status(400).json({ error: 'Invalid request' });
}
const city = req.body.city;
const email = req.user.email;
User.findOneAndUpdate({ email: email }, { city: city }, (err, user) => {
if (err) {
return res.status(500).json({ error: err.message });
}
res.json({ message: 'City saved successfully' });
});
});
I am doing like this on post req:
{
"email": "[email protected]",
"city": "New York"
}
And also tried this on post req:
{
"city": "New York"
}
CodePudding user response:
I think it is because of your condition . req.user & req.user.email maybe for authenticated middleware . you must add middleware to your route or using this --->
router.post('/save', (req, res) => {
if (!req.body || !req.body.city) {
return res.status(400).json({ error: 'Invalid request' });
}
const city = req.body.city;
const email = req.user.email;
User.findOneAndUpdate({ email: email }, { city: city }, (err, user) => {
if (err) {
return res.status(500).json({ error: err.message });
}
res.json({ message: 'City saved successfully' });
});
});