英文:
Why my api is not working as expected? error Invalid request
问题
Your API is not working as expected because it's returning an "Invalid request" error when certain conditions are not met. Here's the translated code snippet:
后端:
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' });
});
});
我在POST请求中这样做:
{
"email": "myemail@gmail.com",
"city": "New York"
}
也尝试了这个POST请求:
{
"city": "New York"
}
Please make sure you provide the "email" and "
英文:
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": "myemail@gmail.com",
"city": "New York"
}
And also tried this on post req:
{
"city": "New York"
}
答案1
得分: 1
以下是您要翻译的内容:
"我认为这是因为您的条件。req.user和req.user.email可能是用于身份验证中间件。您必须在路由上添加中间件或使用以下方法--->
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' });
});
});
英文:
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' });
});
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论