javascript - 获取帖子时数据未定义
问题描述
所以我尝试制作一个注册表单,将用户名、密码和电子邮件地址发布到我的 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
}
有人可以帮我检测错误吗?
解决方案
当你这样做时:
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...
});
推荐阅读
- php - 托管项目时出现连接问题:SQLSTATE[HY000] [2002] Connection denied
- ubuntu - 无法在默认位置找到新创建的 CouchDB 数据库文件 ./data
- swift - 如何创建关系是一对多的数据库 Firebase?
- javascript - 如何使用 Immer 从减速器返回初始状态?
- python - 使用 python docxtpl 库和 MS word 生成已经扩展的目录
- c# - 在创建特定模式时遇到问题
- javascript - 如何从使用 insertRule 添加的样式中检索 CSS 文本?
- python - 你如何在你的python代码上添加点
- python - 重新排列数组以在 Python 中按顺序排列
- javascript - rails资产管道javascript“SyntaxError:意外的令牌导出”