Javascript 获取帖子时数据未定义

Javascript 获取帖子时数据未定义,javascript,react-native,express,Javascript,React Native,Express,所以我试图制作一个注册表单,将用户名、密码和电子邮件地址发布到我的ExpressJs服务器并保存它,但对象到达时没有定义。。。这是我的react应用程序中的JS代码: let RegDetails = { userName: userName, password: password, email: email } let regJSONED = JSON.stringify(RegDetails); fetch('http://localhost:4000/user

所以我试图制作一个注册表单,将用户名、密码和电子邮件地址发布到我的ExpressJs服务器并保存它,但对象到达时没有定义。。。这是我的react应用程序中的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
}
{regJSONED: {\"userName\":\"joe\",\"password\":\"secret\",\"email\":\"joe@example.com\"}}
有人能帮我检测错误吗?

当您这样做时:

body:  {regJSONED}
…您正在将
body
设置为如下所示的对象:

{
userName: undefined,
  password: undefined,
  email: undefined
}
{regJSONED: {\"userName\":\"joe\",\"password\":\"secret\",\"email\":\"joe@example.com\"}}
…它
fetch
然后可能会转换为字符串,很可能是
“[object object]”

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

body:  regJSONED

还请注意,
标题
应为
标题
(全部小写)


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

所以可能是这样的:

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

看起来像是头上的打字错误:

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


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

}).then(data => data && console.log(data.json()));
更好的示例请参见:

尝试
body:regJSONED
而不是
body:{regJSONED},
非常感谢你!