Trying to access response data using fetch

青春壹個敷衍的年華 提交于 2019-12-09 09:45:07

问题


I'm trying something simple where I make a request from the front end of my app using the fetch API like so

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

fetch(request).then((response) => {
    console.log(response);
});

I am handling this request on the server like so,

app.get('/add', (req, res) => {
    const data = {
        "number1": "2", 
        "number2": "4"
    };
    res.send(data);
});

However, when I try to access my data on the front end console.log(response), I get the following object

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

The response body is empty. I assumed that's where the data would show up? How do I pass data effectively from the server?


回答1:


Okay, this works on my front end

fetch(request).then((response) => {
    console.log(response);
    response.json().then((data) => {
        console.log(data);
    });
});

The key part was the resolution of the promise chain.

Similar question here JavaScript fetch API - Why does response.json() return a promise object (instead of JSON)?



来源:https://stackoverflow.com/questions/45366789/trying-to-access-response-data-using-fetch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!