所以我尝试制作一个注册表单,将用户名、密码和电子邮件地址发布到我的 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
}
有人可以帮我检测错误吗?
最佳答案
当你这样做时:
body: {regJSONED}
...您将 body
设置为如下所示的对象:
{regJSONED: {\"userName\":\"joe\",\"password\":\"secret\",\"email\":\"joe@example.com\"}}
...fetch
然后可能会转换为字符串,很可能是“[object Object]”
。
我认为您只是想发送存储在 regJSONED
中的字符串;不要将其包装在 {}
中:
body: regJSONED
<小时/>
另请注意,fetch
, Headers
应该是 headers
(全部小写)。
另请注意,示例中的data
将是一个response
对象。您需要阅读响应正文才能使用它(请参阅 fetch
)。还有一些错误处理问题(包括 the fetch
footgun (这是我贫血的小博客上的一篇文章))。
所以可能是这样的:
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...
});
关于javascript - 获取帖子时数据到达未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59092305/