17

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
  • try change res.send(data); to res.end(data);?
    – Val
    Jul 28, 2017 at 6:57

3 Answers 3

48

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)?

0
4

Like @random_coder_101, you can also write it without nesting:

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

Could also split in to two like this

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.