我的后端路由有问题,其中 res.status().send()
只会向客户端发送状态代码,但不会向客户端发送所定位的对象在 send()
中。
这是我的代码(为简洁起见删除了所有代码但问题所在):
exports.user_signup = (req, res) => {
const { body } = req;
const { companyName, password, email } = body;
User.find({ email: email }, (err, previousUsers) => {
if (err) {
return res.status(400).send({
message: "There was an issue signing up."
});
} else if (previousUsers.length > 0) {
return res.status(403).send({
message: "Records show this email is linked to another account."
});
}
}
当我从客户端发出我的获取请求
时,响应只从服务器返回状态代码
,但响应中没有任何地方是中的对象>send()
服务器上的方法。只是随地吐痰,我向它扔了 res.status(200).json(object)
以将对象作为 json
发送,但无济于事。
这是我从客户端获取的请求:
fetch("http://localhost:3000/users/accounts/", {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(userData)
}).then(response => console.log(response));
}
为了显示我得到的响应,我特意将一些表单数据从客户端发布到会抛出 403 错误的路由,这是我在浏览器控制台中得到的响应:
Response {type: "basic", url: "http://localhost:3000/users/accounts/", redirected: false, status: 403, ok: false, …}
所以我能够成功地将状态从路由发送回客户端,但是我终究无法弄清楚为什么 send()
没有将对象与其一起发送.
最佳答案
从 fetch()
返回的响应的 body
是一个 ReadableStream
。您需要对其进行处理以将其变成可用的东西。通常你会调用 response.json()
将其解析为 JSON 对象:
fetch("http://localhost:3000/users/accounts/", {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(userData)
})
.then(response => response.json())
.then(response => console.log(response));
}
关于javascript - Node/Express - res.status().send() 只发送状态但不发送对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53551851/