Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch API get raw value from Response

I use React-Native request some data, here is my code:

    fetch('https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json')
      .then((response)=>{
        return response.json()
      })
      .then((responseJSON)=>{
        callback(responseJSON)
      })
      .catch((error)=>{
        console.error(error);
      })
      .done()

I see the response is a Response object, and the json function code is return this.text().then(JSON.parse), I'm confused that what is the parameter of theJSON.parse? Is that the response raw value? How can I get it?

like image 657
ZeroChow Avatar asked Feb 20 '17 07:02

ZeroChow


People also ask

How do I get data from response fetch?

The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.

How do I get fetch from API response?

Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.

Does fetch return a value?

The fetch() method returns a promise that can either be resolved or not. Thus, this method always returns a value and the only possible case where it may fail to return anything is a server error.

How do I get json from fetch response?

To get JSON from the server using the Fetch API, you can use the response. json() method. The response. json() method reads the data returned by the server and returns a promise that resolves with a JSON object.


1 Answers

Here's how you'd do what you want. In my case I wanted to manually parse the JSON because a certain character (\u001e) is improperly parsed by the in-built JSON parser.

Change from:

fetch(url)
    .then(response => response.json()) 
    .then((data) => {
        data....

to:

fetch(url)
    .then(response => response.text()) 
    .then((dataStr) => {
        let data = JSON.parse(dataStr);
        data...
like image 133
AndrewL Avatar answered Oct 05 '22 02:10

AndrewL