Trying to access response data using fetch

后端 未结 2 1062
鱼传尺愫
鱼传尺愫 2021-02-07 21:12

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/a         


        
相关标签:
2条回答
  • 2021-02-07 21:51

    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 讨论(0)
  • 2021-02-07 22:09

    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)
    
    0 讨论(0)
提交回复
热议问题