Reputation: 129
I'm trying to make a post request with this code:
fetch(`${API_URL}`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
// body
}),
user: JSON.strigify(user)
});
The problem is, on the backend, the server is returning undefined for req.user.
Upvotes: 2
Views: 536
Reputation: 1
You can not send user as a top-level property in the fetch request. You can either include them in body or headers. But if you are using GET request, you might not be able to include in request body.
Here's the solution with user added in headers.
fetch(`${API_URL}`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-user-data': JSON.stringify(user) // You can send in user key as well
}
}).then(async (result) => {
console.log(await result.json());
}). catch((error)=>{
console.log(error)
});
Upvotes: 0
Reputation: 112787
It's hard to say for sure what might be wrong without seeing how you handle the request in the backend, but you most likely must put the user
object in the body
.
This would however end up in req.body.user
in the backend, not req.user
.
fetch(`${API_URL}`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
user
})
});
Upvotes: 2