尝试使用 fetch 访问响应数据

Trying to access response data using fetch

我正在尝试一些简单的事情,我使用 fetch API 从我的应用程序的前端发出请求,就像这样

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);
});

但是,当我尝试在前端访问我的数据时 console.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);
    });
});

关键是promise链的解析。

这里有类似的问题

也可以这样一分为二

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)

和@random_coder_101一样,不嵌套也可以这样写:

fetch(request)
  .then(resp => resp.json())
  .then(data => { console.log(data) })
  .catch(err => { console.log(err) });