javascriptaxios

Unable to pass bearer token in axios.get request


I am trying to make an api call using axios , if i use the put,post or delete method then i am able to pass bearer token in the header , but no in the get method

const config = { headers: { Authorization: `Bearer ${token}` } };

this get request doesn't work

axios.get(
        "http://localhost:3001/api/message/",
        {
          chatId: "661925ba21df3cb3dc4958be",
        },
        config
      )
      .then(async (results) => {
        console.log(results);
      })
      .catch((error) => {
        console.log(error);
      });

Bearer token is not present in get request but this post request works

axios.post(
        "http://localhost:3001/api/message/",
        {
          chatId: "661925ba21df3cb3dc4958be",
        },
        config
      )
      .then(async (results) => {
        console.log(results);
      })
      .catch((error) => {
        console.log(error);
      });

Bearer token is present in post request

I just changed get to post and the bearer token is included in the header , what's the issue with get method?


Solution

  • You are calling the request wrongly, you call the axios.get() request slightly different from how you do axois.post()

    axios.get(url, config) take the API URL as the first parameter and the config as the second parameter since you can't ideally send a body with a get request when it comes to https unlike in post where axios.post(url,body,config) where the first parameter is the url, second is the request body and third is the config

    Update your code like this:

      const config = { headers: { Authorization: `Bearer ${token}` } };
    
      axios.get("http://localhost:3001/api/message/",config)
          .then(async (results) => {
            console.log(results);
          })
          .catch((error) => {
            console.log(error);
          });
    

    If you need to pass data in a get request you can do that in the query parameter like this

     axios.get("http://localhost:3001/api/message?chatId=661925ba21df3cb3dc4958be",config)
          .then(async (results) => {
            console.log(results);
          })
          .catch((error) => {
            console.log(error);
          });