0

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 };
    }
  }
);
Dhinesh
  • 141
  • 1
  • 4
  • 18
  • Could you provide a screenshot from the error and other info from your browser console? Also, shouldn't you use JSON.stringify() on the body? – Jeroen Jul 22 '22 at 12:02
  • Yes. I got 422 response error while trying JSON.Stringify() on the body. – Dhinesh Jul 22 '22 at 12:05
  • Try JSON.stringify({user_id: '6000', title: 'wakeup', status: 'pending', due_on: '2022-07-22T10:40:36.630Z+10:40'}) – Ram Rana Jul 22 '22 at 12:11
  • https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch For more understanding. – Ram Rana Jul 22 '22 at 12:12

1 Answers1

1

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'})
  
monim
  • 3,641
  • 2
  • 10
  • 25