在javascript(和Node.js)中获取GET请求的结果

在javascript(和Node.js)中获取GET请求的结果,javascript,node.js,http,get,Javascript,Node.js,Http,Get,当我点击一个按钮时,我试图从Node.js服务器获取一个基本的get请求 server.js const express=require('express'); 常量app=express(); 应用程序使用(快速静态(“/公共”); 应用程序监听(8080,()=>{ log(`Service started on port 8080.`); }); app.get('/clicks',(req,res)=>{ res.send(“foobarbaz”); }) client.js docu

当我点击一个按钮时,我试图从Node.js服务器获取一个基本的get请求

server.js

const express=require('express');
常量app=express();
应用程序使用(快速静态(“/公共”);
应用程序监听(8080,()=>{
log(`Service started on port 8080.`);
});
app.get('/clicks',(req,res)=>{
res.send(“foobarbaz”);
})
client.js

document.getElementById(“按钮”).addEventListener(“单击”,显示结果);
函数showResult(){
获取('/clicks',{method:'GET'})
.然后(功能(响应){
if(response.ok){
返回响应;
}
抛出新错误(“获取失败”);
})
.then(功能(数据){
控制台日志(数据);
})
.catch(函数(错误){
console.log(错误);
});
}
但是,控制台日志显示:

Response{type:“basic”,url:http://localhost:8080/clicks,重定向:false,状态:200,确定:true,…}
正文:(……)
bodyUsed:假
标题:标题{}
好的,没错
重定向:错误
现状:200
状态文本:“确定”
类型:“基本”
url:“http://localhost:8080/clicks"
__原型:响应
我怎样才能得到我的“foobarbaz”

如果我转到
localhost:8080/单击
,文本就会显示在那里

另外,
response
似乎已经是一个javascript对象--
response.json()
不起作用。
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);
        });
}

您的服务器代码不响应JSON,因此
response.JSON()
不起作用。您需要在响应请求时设置内容类型标头。我建议看一些教程,了解如何配置express以响应JSON。这个