我试图在发现用户但不成功之后将数据保存到数据库
const Profile = require("../../models/Profile");
const User = require("../../models/User");
router.post('/profile',(req,res) => {
User.findOne({
"_id": id
}).then(user => {
if (!user) {
return res.status(400).json({
email: "User not found"
});
} else {
const newProfile = new Profile({
companyname: req.body.companyname,
userid: user._id
});
newProfile.save().then((user) => {
res.json(user)
}).catch(err => console.log(err));
res.send(newProfile)
}
}).catch(err => {
return res.status(400).json({
message: "User not found"
});
});
})
我期望将数据保存在配置文件集合(而不是用户集合)中,但出现如下错误消息
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (/Users/guest/Desktop/mernapp/node_modules/express/lib/response.js:775:10)
at ServerResponse.send (/Users/guest/Desktop/mernapp/node_modules/express/lib/response.js:174:12)
at ServerResponse.json (/Users/guest/Desktop/mernapp/node_modules/express/lib/response.js:271:15)
at newProfile.save.then (/Users/guest/Desktop/mernapp/routes/api/profile.js:59:28)
at process._tickCallback (internal/process/next_tick.js:68:7)
答案 0 :(得分:0)
res.send(newProfile)需要删除。 我已经更新了代码,希望对您有所帮助。
router.post('/profile',(req,res) => {
User.findOne({
"_id": id
}).then(user => {
if (!user) {
return res.status(400).json({
email: "User not found"
});
} else {
const newProfile = new Profile({
companyname: req.body.companyname,
userid: user._id
});
newProfile.save().then((newProfileRes) => {
res.status(200);
res.json(newProfileRes);
}).catch(err => {
console.log(err);
res.json({message : 'Profile not Created'});
});
}
}).catch(err => {
return res.status(400).json({
message: "User not found"
});
});
})