英文:
AJAX post request gives value undefined
问题
I am using javascript, AJAX and Node js and I cannot get a value on server side when I do a post request. I have the following to test it and it says value undefined.
The app.js file
app.use(express.json());
app.post("/admin-usercategories/:id/edit", async function (req, res) {
    try {
        console.log('Title - ' + req.body.title);
        res.json({message: 'Insertion completed!'})
    } catch (error) {
        res.status(500).json(error);
    }
})
In my javascript file:
async function saveUsercategories(displayElement, userId) {
    const comment = { title: "HELLO", text: "How are you?"};
    await fetch(`/admin-usercategories/${userId}/edit`, {
        method: 'POST',
        body: JSON.stringify(comment)
    });            
}
英文:
I am using javascript, AJAX and Node js and I cannot get a value on server side when I do a post request. I have the following to test it and it says value undefined.
The app.js file
app.use(express.json());
app.post("/admin-usercategories/:id/edit", async function (req, res) {
    try {
        console.log('Title - ' + req.body.title);
        res.json({message: 'Insertion completed!'})
    } catch (error) {
        res.status(500).json(error);
    }
})
In my javascript file:
async function saveUsercategories(displayElement, userId) {
    const comment = { title: "HELLO", text: "How are you?"};
    await fetch(`/admin-usercategories/${userId}/edit`, {
        method: 'POST',
        body: JSON.stringify(comment)
    });            
}
答案1
得分: 0
查看上传 JSON 数据示例的 MDN 文档。
您尚未设置Content-Type请求头,因此fetch将默认(基于您将字符串传递给body)告知服务器您正在发送text/plain,这不会触发 JSON 请求体解析中间件。
await fetch(`/admin-usercategories/${userId}/edit`, {
    method: 'POST',
    body: JSON.stringify(comment),
    headers: {
        "Content-Type": "application/json"
    }
});
英文:
See the "Uploading JSON data" example from MDN.
You haven't set a Content-Type request header, so fetch will default (based on you passing a string to body) to telling the server that you are sending text/plain which doesn't trigger the JSON body parsing middleware.
await fetch(`/admin-usercategories/${userId}/edit`, {
    method: 'POST',
    body: JSON.stringify(comment),
    headers: {
        "Content-Type": "application/json"
    }
});            
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论