I am making a fetch call to my back end, here is the call.
const response = await fetch(apiUrl + '/recipes', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Token token=${user.token}`
},
body: JSON.stringify({
recipe: {
recipeId: uri
}
})
})
I am making a fetch call to my back end, here is the call.
const response = await fetch(apiUrl + '/recipes', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Token token=${user.token}`
},
body: JSON.stringify({
recipe: {
recipeId: uri
}
})
})
Then this is the route I send the call to on my backend
router.post('/recipes', requireToken, (req, res) => {
req.body.recipe.owner = req.user.id
Recipe.create(req.body.recipe)
.then(recipe => {
console.log('Recipe object saved is', recipe)
res.status(201).json({ recipe: recipe.toObject() })
})
.catch(err => handle(err, res))
})
When I do this, the correct object logs right before it sends back. Here is an example of what gets logged
{ __v: 0,
updatedAt: 2018-10-19T15:47:16.809Z,
createdAt: 2018-10-19T15:47:16.809Z,
recipeId: 'http://www.edamam./ontologies/edamam.owl#recipe_7dae4a3b1f6e5670be3c2df5562e4782',
owner: 5bc9fc6a3682194cdb8d6fa5,
_id: 5bc9fc843682194cdb8d6fa7 }
However, when I console.log what I get back on the front end, I get this.
Response {type: "cors", url: "http://localhost:4741/recipes", redirected: false, status: 201, ok: true, …}
body: ReadableStream
bodyUsed: true
headers: Headers {}
ok: true
redirected: false
status: 201
statusText: "Created"
type: "cors"
url: "http://localhost:4741/recipes"
__proto__: Response
On the call, it does record the action with my database, so the information gets saved, and is logged right before it should be sent back, however the proper information is not sent back. Thank you ahead of time for any response.
Share Improve this question edited Oct 19, 2018 at 22:00 Julio Betta 2,2951 gold badge25 silver badges25 bronze badges asked Oct 19, 2018 at 17:26 Julian SirkinJulian Sirkin 471 silver badge3 bronze badges1 Answer
Reset to default 7Since you're using fetch
to make the request, the response is encapsulated in the Response
object, and to access it you have to call the async method json()
. Just like the following:
const Response = await fetch(apiUrl + '/recipes', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Token token=${user.token}`
},
body: JSON.stringify({
recipe: {
recipeId: uri
}
})
});
const json = await Response.json();
console.log(json);
You can play with another example in your chrome console.
(async () => {
const Response = await fetch('https://jsonplaceholder.typicode./todos/1');
const res = await Response.json();
console.log(res);
})();
UPDATE
Another way to do that is:
(async () => {
const response = await (
await fetch('https://jsonplaceholder.typicode./todos/1')
).json();
console.log(response);
})();
I hope this helps.