NodeJS和Express在客户端读取JSON响应



我正试图使用Express做一个简单的服务器,但我很难阅读作为响应一部分发送给客户端的信息。

这是我在服务器上的一个端点:

app.post('/click',(req, res) =>{
res.status(200).json({'message' : 'You clicked the button!'});
}

这是使用端点向服务器发出请求的客户端:

button.addEventListener('click', function(e) {
fetch('/click', {method: 'POST'})
.then(function(response) {
if(response.ok) {
return response.json()
}
throw new Error('Request failed.');
})
.then(function(data){
var serverInfo = JSON.parse(data)
})
.catch(function(error) {
console.log(error);
});
});

这不起作用,尝试了更多的事情,比如不使用JSON.parse,但仍然不起作用,你知道我是如何在客户端读取服务器响应的吗??

快速查看fetch,您调用了错误的端点。

/test/success而不是/click

希望是这样,

欢呼!

有一个拼写错误return response.json应该是return response.json()。试试这个。

小提示:在then块中不处理错误,使用catch块抛出错误;(

button.addEventListener('click', function(e) {
fetch('/test/success', {method: 'POST'})
.then(function(response) {
return response.json()
})
.then(function(data){
console.log('Do what you want => ', data)
})
.catch(function(error) {
console.log(error);
});
});

您可以使用以下方法在客户端中获取JSON

button.addEventListener('click', function(e) {
fetch('/click', {method: 'POST'})
.then(async function(response) {
const result = await response.json();
console.log(result.message);
})
});

最新更新