问题描述
在我的社交媒体应用程序中,当用户对帖子发表评论时,它会抛出一个 500 Internal Server Error.
控制台状态 POST https://shielded-journey-88539.herokuapp.com/https://us-central1-myapp-1d191.cloudfunctions.net/api/post/3Y7OcHJXXXa0ilBeq35u/comment 500 (Internal Server Error)
当我检查 commentOnPost
上的 Postman
路由时,响应返回 Status 200
,但正文返回 Invalid Host Header
。
// Comment on a Post API
exports.commentOnPost = (req,res) => {
if (req.body.body.trim() === '') {
return res.status(400).json({ comment: 'Cannot be empty' });
}
const newComment = {
body: req.body.body,createdAt: new Date().toISOString(),postId: req.params.postId,userHandle: req.user.handle,profileImage: req.user.profileImage
};
db.doc(`/posts/${req.params.postId}`)
.get()
.then(doc => {
if (!doc.exists) {
return res.status(404).json({ error: 'Post does not exist.' });
}
// after gaining access to document,use prefix reference to update comment count
return doc.ref.update({ commentCount: doc.data().commentCount + 1 })
})
.then(() => { // add newComment to comments collection
return db.collection('comments').add(newComment);
})
.then(() => {
res.json(newComment);
})
.catch(err => {
console.log(err);
res.status(500).json({ error: 'Something went wrong' });
});
};
当我在 console.log(commentData)
内 dataSlice/submitComment
时,它只返回 req.body.body
而不是 newComment
对象的其余部分,从 commentOnPost
路由返回。
// submitComment of dataSlice
export const submitComment = (postId,commentData) => dispatch => {
console.log(commentData)
return axios
.post(`/post/${postId}/comment`,commentData)
.then(res => {
dispatch(submitTheComment(res.data))
dispatch(clearErrors());
})
.catch(err => dispatch(setErrors(err.response)))
};
我使用的是我自己的 Heroku 代理服务器。
// App.jsx
axios.defaults.baseURL =
'https://shielded-journey-88539.herokuapp.com/https://us-central1-myapp-1d191.cloudfunctions.net/api';
// package.json
"proxy": "https://shielded-journey-88539.herokuapp.com/https://us-central1-myapp-1d191.cloudfunctions.net/api"
我做错了什么?
解决方法
你能试试这个代码吗,还有console.log(commentData)
,commentData
在哪里?
exports.commentOnPost = (req,res) => {
if (req.body.body.trim() === '') {
return res.status(400).json({ comment: 'Cannot be empty' });
}
const newComment = {
body: req.body.body,createdAt: new Date().toISOString(),postId: req.params.postId,userHandle: req.user.handle,profileImage: req.user.profileImage
};
console.log("newComment: ",newComment)
db.doc(`/posts/${req.params.postId}`).get()
.then(doc => {
if (!doc.exists) {
return res.status(404).json({ error: 'Post does not exist.' });
}
// after gaining access to document,use prefix reference to update comment count
return doc.ref.update({ commentCount: doc.data().commentCount + 1 });
}).then(() => {
// add newComment to comments collection
db.collection('comments').add(newComment);
res.status(200).json(newComment);
}).catch(err => {
console.log("Error in Catch commentOnPost: ",err);
res.status(500).json({ error: 'Something went wrong' });
});
};