Reputation: 4192
In node js i made this api:
app.get("/user", (req, res) => {
res.send('my data from server')
});
So, now, when i fetch data using:
fetch('http://localhost:1000/user', {
method: "GET",
})
.then(data => console.log(data))
.catch((error) => {
console.error('Error:', error);
});
I expect in console.log(data)
besides:
Response {type: "cors", url: "http://localhost:1000/user", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:1000/user"
__proto__: Response
and: data: 'my data from server', so at the end i expect something like this:
Response {type: "cors", url: "http://localhost:1000/user", redirected: false, status: 200, ok: true, …}
data: 'my data from server'
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:1000/user"
__proto__: Response
Question: Why i can not get data from the server as i expect?
Upvotes: 0
Views: 405
Reputation: 188
fetch('http://localhost:1000/user', {
method: "GET",
})
.then(res => console.log(res.body))
.catch((error) => {
console.error('Error:', error);
});
Your data is inside res.body!! (I have renamed data to res as it is kind of a standard)
Upvotes: 0
Reputation: 14904
You forgot to extract the body.
The Body mixin defines the following methods to extract a body (implemented by both Request and Response). These all return a promise that is eventually resolved with the actual content.
In your case its just a text, but it could also be JSON depends on what your server response.
fetch('http://localhost:1000/user', {
method: "GET",
})
.then(response => response.text())
.then(data => console.log(data))
.catch((error) => {
console.error('Error:', error);
});
Upvotes: 2