我不確定發生了什么。我使用 localhost 在 dev 中設定了所有相同的代碼,并且一切正常。我將我的應用程式托管到 Vercel,并將我的 API 托管到 heroku,從我可以看出 API 運行良好。現在的問題是,當我發出發布請求時,我在瀏覽器中收到 400 Bad Request 錯誤,但它仍然發出請求并發布到我設定的資料庫。任何幫助都值得贊賞。我用 NEXT.js 在 MERN 堆疊中構建了這個應用程式
這是我的客戶端 Post 請求
const postSubmit = async e => {
e.preventDefault();
try {
const { data } = await axios.post('/create-post', { content, image });
if(data.error) {
toast.error(data.error);
} else {
setPage(1);
newsFeed();
toast.success("Post created");
setContent('');
setImage({});
// socket.emit('new-post', data);
}
} catch(e) {
console.log(e);
}
}
這是我對發布請求的服務器端處理
export const createPost = async (req, res) => {
const { content, image } = req.body;
if(!content.length) {
return res.json({
error: 'Content is required'
})
}
try {
const post = new Post({ content, image, postedBy: req.user._id });
await post.save();
const postWithUser = await Post.findById(post._id).populate('postedBy', '-password -secret');
res.json(postWithUser);
} catch (e) {
console.log(e);
res.sendStatus(400);
}
};
這是瀏覽器告訴我的
Chrome 瀏覽器資訊
uj5u.com熱心網友回復:
這很可能是由 MongoDB 連接字串 (URI) 上的拼寫錯誤引起的,類似于這個答案。
在鏈接的答案中,拼寫錯誤是&w=majority;. 在您的情況下,該值是 某種方式majorityDATABASE=,因此請仔細檢查您的 MongoDB 連接字串并嘗試洗掉DATABASE=寫關注引數中的額外內容。
uj5u.com熱心網友回復:
這可能是因為該await Post.findById()呼叫沒有找到一個結果,當你嘗試呼叫它可以拋出一個錯誤res.json(postWihUser)。如果postWithUser未定義,則會導致錯誤。
發生錯誤時,服務器終端會記錄什么?這應該可以幫助您確定問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/352438.html
