AJAX POST 请求返回值为 undefined。

huangapple go评论77阅读模式
英文:

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"
    }
});            

huangapple
  • 本文由 发表于 2023年5月11日 16:51:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76225787.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定