-1

I am having a difficult time understanding why my API call does not work in axios (relatively new to JS). I have built an API server that takes in an Authorization header with a JWT token.

Here is my POST request workflow in Python:

resp = requests.post('http://127.0.0.1:8000/api/v1/login/access-token', data={'username': 'admin@xyz.com', 'password': 'password'})
token = resp.json()['access_token']

test = requests.post('http://127.0.0.1:8000/api/v1/login/test-token', headers={'Authorization': f'Bearer {token}'})
# ALL SUCCESSFUL

Using axios:

  const handleLogin = () => {
    const params = new URLSearchParams();
    params.append('username', username.value);
    params.append('password', password.value);
    setError(null);
    setLoading(true);
    axios.post('http://localhost:8000/api/v1/login/access-token', params).then(response => {
      console.log(response)
      setLoading(false);
      setUserSession(response.data.access_token);
      props.history.push('/dashboard');
    }).catch(error => {
      setLoading(false);
      console.log(error.response)
      if (error.response.status === 401) {
        setError(error.response.data.message);
      } else {
        setError("Something went wrong. Please try again later.");
      }
    });
  }
// the above works fine

// however:
  const [authLoading, setAuthLoading] = useState(true);

  useEffect(() => {
    const token = getToken();
    if (!token) {
      return;
    }

    axios.post(`http://localhost:8000/api/v1/login/test-token`, {
      headers: {
        'Authorization': 'Bearer ' + token
      }
    }).then(response => {
      // setUserSession(response.data.token);
      console.log('we made it')
      setAuthLoading(false);
    }).catch(error => {
      removeUserSession();
      setAuthLoading(false);
    });
  }, []);

  if (authLoading && getToken()) {
    return <div className="content">Checking Authentication...</div>
  }
// RETURNS A 401 Unauthorized response...

What is different about the two above requests? Why does the axios version return different results than requests?

In my API, CORS have been set to *, and I know that the token within Axios is being saved properly in sessionStorage.

Any ideas?

sgerbhctim
  • 3,420
  • 7
  • 38
  • 60
  • Please have a look at [this answer](https://stackoverflow.com/a/73096718/17865804) and [this answer](https://stackoverflow.com/a/71023536/17865804), as well as [this](https://stackoverflow.com/a/70636163/17865804) and [this](https://stackoverflow.com/a/70975923/17865804). – Chris Feb 05 '23 at 04:45

2 Answers2

0

As far as I can see you are passing your username and password in axios as params and as body data in your python request, I am not sure if your backend expects it as params or body data but try changing const params = new URLSearchParams(); to const params = new FormData(); if the problem is that the backend isn't getting the body data it needs. The best thing I could recommend is checking your browser network tab and seeing what exactly the problem is when you hit your server.

  • Thanks a bunch! So the `handleLogin` request is working just fine with `URLSearchParams`.. the issue comes when I try to call the `test-token` endpoint passing `headers` as I do on the Python `requests` end. Is there a difference in the way I should be passing `headers` through `axios` as well? – sgerbhctim Apr 27 '20 at 14:56
  • oh wow i read below works fine instead of above, hmm well from the looks of it they are identical requests, have you checked the actual request? Also if you are building a larger application I recommend looking into creation of axios instances. You create them once and they share their config across all calls and you can add interceptors onto them to further help you handle your requests and responses. – Alem Tuzlak Apr 27 '20 at 15:43
0

It's because the params that has the "axios.post" method. First param is endpoint, second one is data you wanna send, and third one is config (there it goes the headers, content-type, etc)

Kevin
  • 16
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Blue Robin Mar 02 '23 at 15:11
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/33928064) – Dhaval Purohit Mar 02 '23 at 17:03