Dhinesh
Dhinesh

Reputation: 139

Why post call made using fetch in my react app fails when the same is successfully executed in postman?

I am making a post API call using fetch in my react app (redux-thunk) and getting a '401-Unauthorized' error. but, I made the same post request in postman with the same Authorization token and it returned a successful response.

While trying multiple fixes, I found that I am able to post requests successfully using the npm request library in a standalone node application. Hence, I assume that I am missing something while making the call using fetch in react application. Unfortunately, I cannot use the request library in my react application as it is deprecated and throwing unwanted errors.

Can someone please help me fix this issue? I added my code below:

export const addTodoAsync = createAsyncThunk(
  "todos/addTodoAsync",
  let token = '22e745f508990f40c97feccf5cf3397f7fbe0ae96f6b7baf051fccbcbb8267df';
  async (payload) => {
     const response = await fetch('https://gorest.co.in/public/v1/todos', {
        method: "POST",
        headers:  {
          Accept: "application/json",
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`
      },  
        body: {user_id: '6000', title: 'wakeup', status: 'pending', due_on: '2022-07-22T10:40:36.630Z+10:40'}
      });


      if (response.ok) {
      let todo = await (response.json()).data;
      return { todo };
    }
  }
);

Upvotes: 0

Views: 110

Answers (1)

monim
monim

Reputation: 4383

change :

body: {user_id: '6000', title: 'wakeup', status: 'pending', due_on: '2022-07-22T10:40:36.630Z+10:40'}
      

to :

body: JSON.stringify({user_id: '6000', title: 'wakeup', status: 'pending', due_on: '2022-07-22T10:40:36.630Z+10:40'})
  

Upvotes: 1

Related Questions