【发布时间】:2020-12-01 01:04:58
【问题描述】:
单击按钮时,我试图从 Node.js 服务器获取基本的 GET 请求。
server.js
const express = require('express');
const app = express();
app.use(express.static("./public"));
app.listen(8080, () => {
console.log(`Service started on port 8080.`);
});
app.get('/clicks', (req, res) => {
res.send("foobarbaz");
})
client.js
document.getElementById("button").addEventListener("click", showResult);
function showResult(){
fetch('/clicks', {method: 'GET'})
.then(function(response){
if(response.ok){
return response;
}
throw new Error('GET failed.');
})
.then(function(data){
console.log(data);
})
.catch(function(error) {
console.log(error);
});
}
但是,控制台日志显示:
Response {type: "basic", url: "http://localhost:8080/clicks", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "basic"
url: "http://localhost:8080/clicks"
__proto__: Response
如何获得我的“foobarbaz”?
如果我转到localhost:8080/clicks,文本会显示在那里。
此外,response 似乎已经是一个 javascript 对象 -- response.json() 不起作用。
【问题讨论】:
-
您的服务器代码没有响应 JSON,所以这就是
response.json()不起作用的原因。响应请求时需要设置 Content-Type 标头。我建议查看一些关于如何配置 express 以响应 JSON 的教程。 documentation talks about this in the Guide section.
标签: javascript node.js http get