Reputation:
I want to fetch data from JSON object which is on my localhost . ..This might be really stupid question but I am beginner in JS.
and is there any other way to fetch data ??
fetch('http://localhost:3000/show')
.then(result => {
console.log(result);
return result.json();
});
.then(data => {
console.log(data);
});
.catch(error => {
console.log(error);
});
this http://localhost:3000/show contains json objects. it has retrieved data from mongoose.
Upvotes: 0
Views: 1186
Reputation: 1370
If your endpoint '/show' returns the json data without any issue, then the below code should console you the json response.
fetch('http://localhost:3000/show')
.then(res => {
console.log(result);
return res.json()
)}
.then(json => console.log(json))
.catch(err => console.log(err));
Upvotes: 0
Reputation: 9167
Remove the semicolons between each .then
call.
Promises use a kind of "monadic" pattern: each method on a promise returns another promise, which has the same API. This means you can chain promise methods indefinitely.
So:
fetch()
.then(/* stuff */)
.then(/* more stuff */)
.catch(/* even more stuff */); // <-- this is the only semicolon
The same is true of many Array methods, so you'll often see code like this:
Object.keys( someObj ) // returns an array
.map(/* iterator function */) // Array.map returns an array
.filter(/* iterator function */) // Array.filter returns an array
.sort(/* comparator function */); // Array.sort returns an array
Again, only one semicolon is needed, because each step of the statement produces an array, and JS lets you anticipate that.
If that doesn't help, you might want to post the error you're getting.
I should add that result.json()
will throw if the server at http://localhost:3000/show
fails to provide the HTTP header Content-Type: application/json
. Even if the response body is entirely valid JSON, the HTTPResponse class refuses to do .json()
if the server doesn't state that the content is json.
Also, if this code is running in a browser, and is served from a different host (or port), you will need to do CORS stuff. See https://stackoverflow.com/a/48287868/814463 for possible help.
Upvotes: 3