首页 > 解决方案 > 获取帖子时数据未定义

问题描述

所以我尝试制作一个注册表单,将用户名、密码和电子邮件地址发布到我的 ExpressJs 服务器并保存,但是对象到达未定义......这是我的反应应用程序中的 JS 代码:

let RegDetails = {
     userName: userName,
    password: password,
    email: email
}
let regJSONED = JSON.stringify(RegDetails);


fetch('http://localhost:4000/users/register', {
    method: 'POST',
    Headers:{
        "Content-Type": "application/json"
    },
    body:  {regJSONED},

}).then(data => console.log(data));

我很确定错误出现在这段代码中,因为当我使用 Postman 以 JSON 格式发布时,正文会按预期到达,但是通过这种获取,正文会像这样到达:

{
userName: undefined,
  password: undefined,
  email: undefined
}

有人可以帮我检测错误吗?

标签: javascriptreact-nativeexpress

解决方案


当你这样做时:

body:  {regJSONED}

...您正在设置body一个如下所示的对象:

{regJSONED: {\"userName\":\"joe\",\"password\":\"secret\",\"email\":\"joe@example.com\"}}

...fetch然后可能会转换为字符串,很可能是"[object Object]".

我想你只是想发送你存储的字符串regJSONED;不要将其包装在{}

body:  regJSONED

另请注意,with fetch,Headers应该是headers(全部小写)。


另请注意,data在您的示例中将是一个response对象。您需要阅读响应的正文才能使用它(请参阅 参考资料fetch)。还有一些错误处理问题(包括footgun (这是我贫血的小博客上的一篇文章)fetch

所以可能是这样的:

let regDetails = {
    userName: userName,
    password: password,
    email: email
}
let regJSONED = JSON.stringify(RegDetails);

fetch('http://localhost:4000/users/register', {
    method: 'POST',
    headers:{
        "Content-Type": "application/json"
    },
    body:  regJSONED,

})
.then(response => {
    if (!response.ok) {
        throw new Error("HTTP error " + response.status);
    }
    return response.text(); // or `.json()` or any of several others, depending on what you expect back
})
.then(data => console.log(data))
.catch(error => {
    // ...handle/report error...
});

推荐阅读