Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 尝试使用fetch访问响应数据_Javascript_Node.js_Fetch Api - Fatal编程技术网

Javascript 尝试使用fetch访问响应数据

Javascript 尝试使用fetch访问响应数据,javascript,node.js,fetch-api,Javascript,Node.js,Fetch Api,我正在尝试一些简单的方法,使用FetchAPI从应用程序前端发出请求,如下所示 let request = new Request('http://localhost:3000/add', { headers: new Headers({ 'Content-Type': 'text/json' }), method: 'GET' }); fetch(request).then((response) => { console.log(res

我正在尝试一些简单的方法,使用FetchAPI从应用程序前端发出请求,如下所示

let request = new Request('http://localhost:3000/add', {
    headers: new Headers({
        'Content-Type': 'text/json' 
    }),
    method: 'GET'
});

fetch(request).then((response) => {
    console.log(response);
});
我在服务器上像这样处理这个请求

app.get('/add', (req, res) => {
    const data = {
        "number1": "2", 
        "number2": "4"
    };
    res.send(data);
});
但是,当我尝试访问前端控制台.log(响应)上的数据时,我得到以下对象

Response {type: "basic", url: "http://localhost:3000/add", redirected: false, status: 200, ok: true…}
body:(...)
bodyUsed:false
headers:Headers
ok:true
redirected:false
status:200
statusText:"OK"
type:"basic"
url:"http://localhost:3000/add"
__proto__:Response

响应主体为空。我想那就是数据显示的地方?如何有效地从服务器传递数据

好的,这在我的前端有效

fetch(request).then((response) => {
    console.log(response);
    response.json().then((data) => {
        console.log(data);
    });
});
关键部分是承诺链的解析


这里类似的问题也可以像这样一分为二

async fetchData() {
        let config = {
          headers: {
            'Accept': 'application/json'  //or text/json
          }
        }
        fetch(http://localhost:3000/add`, config)
          .then(res => {
            return res.json();
          }).then(this.setResults);

          //setResults
          setResults(results) {
          this.details = results;

          //or: let details = results

          console.log(details)  (or: this.details)

尝试更改
res.send(数据)至<代码>结束(数据)?非常感谢,它真的很有效。我被困了几个小时,终于找到了它