Node.js res.json()和res.send(),不工作,但仍然可以更改状态代码



我几乎读过关于这方面的每一个线程,但仍然不知道出了什么问题。

客户端不会接收到res.send((、res.json((、res.write((res.end((提供的任何信息。但我知道信息正在发送和存储,因为数据库正在更新,我知道有响应,因为我可以console.log对象,如果我更改服务器的状态代码(例如,200对201(,打印在客户端的响应会反映这一点。

客户端通过邮件将电子邮件发送到服务器。

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,状态:201,确定:true,…}

成功:未定义

这是相关的服务器端代码

Path调用函数

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()的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根本没有任何用处。没有任何东西捕捉到它,所以它没有任何好处。

最新更新