当我点击一个按钮时,我试图从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
我怎样才能得到我的“足球”?
如果我去localhost:8080/clicks
,文本就会出现在那里。
此外,response
似乎已经是一个javascript对象-- response.json()
不工作。
发布于 2020-11-30 09:04:58
send()
参数应该是JSON。将server.js
更改为
app.get('/clicks', (req, res) => {
res.send({result:"foobarbaz"});
})
现在,您将在client.js
中接收一个JSON作为响应,其结果可以作为
function showResult() {
fetch('/clicks', { method: 'GET' })
.then(function (response) {
if (response.ok) {
return response.json();
}
throw new Error('GET failed.');
})
.then(function (data) {
console.log(data.result);
})
.catch(function (error) {
console.log(error);
});
}
https://stackoverflow.com/questions/65077442
复制相似问题