[英]Node.js res.json() and res.send(), not working but still able to change status code
我已经阅读了几乎所有关于此的主题,但仍然无法弄清楚出了什么问题。
客户端不会收到任何信息,无论是 res.send()、res.json()、res.write() res.end()。 但是我知道信息正在发送和存储,因为数据库正在更新,并且我知道有响应,因为我可以控制台记录 object 并且如果我更改服务器的状态代码(例如 200 与 201)打印的响应在客户端反映了这一点。
客户端通过邮寄方式将 email 发送到服务器。
var object = JSON.stringify({
email: myemail,
});
await fetch('http://localhost:4000/api/subscriber/', {
method: 'POST',
body: object,
headers: {
'Content-Type': 'application/json'
}
}).then(res => {
res.json();
console.log(res);})
.then(response => console.log('Success:', response))
.catch(error => console.error('Error:', error));
当我运行它时,这些是日志:
响应 {type: "cors", url: "http://localhost:4000/api/subscriber/", 重定向: false, status: 201, ok: true, ...}
成功:未定义
这是相关的服务器端代码
路径调用一个 function
app.post('/api/subscriber/', (request, response) => {
db.createSubscriber(request, response);
})
然后将信息存储在数据库中并发送响应。 这就是问题所在——我尝试在这里发送的任何内容——甚至随机文本都不会显示,但我知道通信正在发生,因为当我更改它时,我可以看到从客户端记录的状态代码。
const createSubscriber = (request, response) => {
const { firstname, lastname, email } = request.body;
const text = //SQL query
const values = [firstname, lastname, email]
pool.query(text, values, (error, results) => {
if (error) {
console.log('error');
response.status(400);
throw error;
} else {
response.status(201).json({status:201,id:results.insertID});
}
return response;
})
}
我尝试了不同的发送、分配变量和使用方法。然后,进行了大量的小调整。 我不知道我在这里做错了什么。
谢谢您的帮助!
使用浏览器中的fetch()
, res.json()
返回一个新的 promise ,您必须等待带有await
或 .then .then()
) 的 promise 才能从中获取数据。
所以,你会这样做:
await fetch('http://localhost:4000/api/subscriber/', {
method: 'POST',
body: object,
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.json()).then(data => {
console.log(data);
}).catch(error => console.error('Error:', error));
此外,在服务器端,您的错误处理需要一些修复。 改变这个:
if (error) {
console.log('error');
response.status(400);
throw error;
}
对此:
if (error) {
console.log(error);
response.sendStatus(400);
}
您必须始终发送响应。 您正在设置错误状态,但从未发送响应。 而且, throw err
根本没有用。 没有什么能抓住它,所以它没有任何好处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.