score:338
in order to access the data from a readablestream
you need to call one of the conversion methods (docs available here).
as an example:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(function(response) {
// the response is a response instance.
// you parse the data into a useable format using `.json()`
return response.json();
}).then(function(data) {
// `data` is the parsed version of the json returned from the above endpoint.
console.log(data); // { "userid": 1, "id": 1, "title": "...", "body": "..." }
});
edit: if your data return type is not json or you don't want json then use text()
as an example:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(function(response) {
return response.text();
}).then(function(data) {
console.log(data); // this will be a string
});
hope this helps clear things up.
score:-1
i just had the same problem for over 12 hours before reading next, just in case this helps anyone. when using nextjs inside your _api page you will need to use json.stringify(whole-response) and then send it back to your page using res.send(json.stringify(whole-response)) and when it's received on the client side you need to translate it back into json format so that it's usable. this can be kinda figured out by reading their serialization section. hope it helps.
score:4
i dislike the chaining thens. the second then does not have access to status. as stated before 'response.json()' returns a promise. returning the then result of 'response.json()' in a acts similar to a second then. it has the added bonus of being in scope of the response.
return fetch(url, params).then(response => {
return response.json().then(body => {
if (response.status === 200) {
return body
} else {
throw body
}
})
})
score:11
if you just want the response as text and don't want to convert it into json, use https://developer.mozilla.org/en-us/docs/web/api/body/text and then then
it to get the actual result of the promise:
fetch('city-market.md')
.then(function(response) {
response.text().then((s) => console.log(s));
});
or
fetch('city-market.md')
.then(function(response) {
return response.text();
})
.then(function(mytext) {
console.log(mytext);
});
score:13
note that you can only read a stream once, so in some cases, you may need to clone the response in order to repeatedly read it:
fetch('example.json')
.then(res=>res.clone().json())
.then( json => console.log(json))
fetch('url_that_returns_text')
.then(res=>res.clone().text())
.then( text => console.log(text))
score:19
little bit late to the party but had some problems with getting something useful out from a readablestream
produced from a odata $batch request using the sharepoint framework.
had similar issues as op, but the solution in my case was to use a different conversion method than .json()
. in my case .text()
worked like a charm. some fiddling was however necessary to get some useful json from the textfile.
score:37
res.json()
returns a promise. try ...
res.json().then(body => console.log(body));
score:79
some people may find an async
example useful:
var response = await fetch("https://httpbin.org/ip");
var body = await response.json(); // .json() is asynchronous and therefore must be awaited
json()
converts the response's body from a readablestream
to a json object.
the await
statements must be wrapped in an async
function, however you can run await
statements directly in the console of chrome (as of version 62).
Source: stackoverflow.com
Related Query
- Retrieve data from a ReadableStream object?
- How to retrieve data from promise object in React JS
- How can I retrieve the data from Promise object in React?
- How to retrieve different type of data from JSON object array and play with it?
- Get object data and target element from onClick event in react js
- How to access data attributes from event object
- React.js: loading JSON data with Fetch API and props from object array
- ReactJS - get json object data from an URL
- React Apollo first object from subscription not being merge into previous data it actually gets removed
- How to retrieve data from firebase in React?
- retrieve data from asyncStorage in react native
- How do I display data from a JSON object using ReactJS?
- How can i get array of object from this data for state and count in reactjs
- How can I extract data from this returned object in an async function?
- How to retrieve data from form using a POST route?
- How to retrieve data from the server using fetch get method and show it in a table
- Display data in a React component from an object where the keys are different but the values are the same
- How can I get the Material-UI DataGrid to read object data from an array?
- How to retrieve data from Redux store using functional components and avoiding useSelector & useDispatch
- Get data from filepond object instance
- How do I retrieve the data from a scanned QR Code?
- How do I correctly add data from multiple endpoints called inside useEffect to the state object using React Hooks and Context API?
- How to retrieve data from date in weather api?
- React iterate over object from json data
- How to retrieve data from custom attribute on option tag in React
- Retrieve data from Apollo store
- Data from the object doesn't convert when using JSON.stringify
- retrieve data from a list of specific IDs in Firebase, follow user and only get their posts
- Client to retrieve data from backend server database table via a websocket connection
- Extract deep down data from JSON Object
More Query from same tag
- Sort By Last Name Data fetched from API In React JS
- How to get query parameters in reactjs
- React Native binary rejected by Apple for using non-public API
- react date range calculate (opened business hours)
- Uncaught Invariant Violation: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead
- How can i restrict user from not selecting other file types using input type file with react and typescript?
- React - get request is getting the correct object but when read into react component the value is undefined
- Unable to submit form data while submitting from React to Node/express using AXIOS
- How can I write Action for redux action generators?
- How can I added a wrapper with styled component in React Modal in Typescript?
- React.js onClick event: TypeError: Cannot read property of undefined
- Passing Data to Another Component OnClick
- React Slick not working
- How do I pass props from from redux store
- Redirects doesn't work on netlify with nextjs
- Can't set scrollTop of HTMLElement in useEffect without timeout function
- Ant Design cannot update initial Value for dynamic Form Item
- Can't load font-awesome with Webpack
- How to get req.query value from Node.js backend to React-Redux front-end?
- Special characters not being rendered properly across different environments
- Importing 'render' from @testing-library/react in a jsx file is erroring out
- React native props typescript
- Node error Cannot read property 'resolve' of undefined
- correct syntax for react higher order component
- Setup react app build folder onto Google Kubernetes
- Unclear benefit of "setLoading" state in React axios
- How to do so that my field must at least be able to contain only numbers and a + in front of the number (if the user wishes)
- React-redux - Console gives "TypeError: props.fetchSearchResults is not a function"
- Why I can't use dispatch a thunk inside useEffect?
- axios response.blob is not a function