Oluwakorede Fashokun
Oluwakorede Fashokun

Reputation: 129

How to add req.user to fetch request

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

Answers (2)

Ya Min Thwe
Ya Min Thwe

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

Tholle
Tholle

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

Related Questions