skip to Main Content

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?

2

Answers


  1. The sytax of axios.get / axios.post is different:

    axios.get('/api', {headers: {}, params: {}});
    
    axios.post('/api', {msg: 'here is your data object'}, {headers: {}, params: {}})
    

    BTW, you can use interceptos to make it easier:

    axios.interceptors.request.use(config => {
       const token = localStorage.getItem('TOKEN')
       if (token) {
          config.headers['Authorization'] = `Bearer ${token}`
       }
    })
    
    Login or Signup to reply.
  2. 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);
          });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search