ChatGPT解决这个技术问题 Extra ChatGPT

Sending the bearer token with axios

In my react app i am using axios to perform the REST api requests.

But it's unable to send the Authorization header with the request.

Here is my code:

tokenPayload() {
  let config = {
    headers: {
      'Authorization': 'Bearer ' + validToken()
    }
  }
  Axios.post( 
      'http://localhost:8000/api/v1/get_token_payloads',
      config
    )
    .then( ( response ) => {
      console.log( response )
    } )
    .catch()
}

Here the validToken() method would simply return the token from browser storage.

All requests are having a 500 error response saying that

The token could not be parsed from the request

from the back-end.

How to send the authorization header with each requests? Would you recommend any other module with react?

I don't think its an axios issue at all. check your validToken() function, it returning somthing that your server does not understand.
I double checked the function and also used the token string here instead of the function,, still the same

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

const bodyParameters = {
   key: "value"
};

Axios.post( 
  'http://localhost:8000/api/v1/get_token_payloads',
  bodyParameters,
  config
).then(console.log).catch(console.log);

The first parameter is the URL. The second is the JSON body that will be sent along your request. The third parameter are the headers (among other things). Which is JSON as well.


You missed a space between bearer and token - then it will work.
Doctor's post: "key: "value" has a quote that should be removed... But fixing that did get the auth to work for my react-native app.
@mediaguru Thx for the comment. I fixed it (I suppose) ! The quote must have been introduce by someone editing the answer...
Bearer should be used with capital B, shouldn't it?
@Alizadeh118 Yes, according to the HTTP spec. But many api's don't insist on the correct capitalization.
T
The Dark Lord

Here is a unique way of setting Authorization token in axios. Setting configuration to every axios call is not a good idea and you can change the default Authorization token by:

import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:1010/'
axios.defaults.headers.common = {'Authorization': `bearer ${token}`}
export default axios;

Some API require bearer to be written as Bearer, so you can do:

axios.defaults.headers.common = {'Authorization': `Bearer ${token}`}

Now you don't need to set configuration to every API call. Now Authorization token is set to every axios call.


Bearer needs to be capitalised for some APIs (I discovered the hard way).
This should be accepted answer. This is better approach.
@FaizanMubasher not if yo use different servers
@Musculaa the question is not about different servers 😊.
for loading token from a function or local storage we need interceptors
S
Stephen Ostermiller

You can create config once and use it everywhere.

const instance = axios.create({
  baseURL: 'https://example.com/api/',
  timeout: 1000,
  headers: {'Authorization': 'Bearer '+token}
});

instance.get('/path')
.then(response => {
    return response.data;
})

Where is the value of token passed from in this example? For my application, the token would be passed back to the api either in the header or body after a successful login.
its here headers: {'Authorization': 'Bearer '+token}
How to pass data if it is an POST request
For those who are wondering from where the value of token can be passed, here is es6 syntax - const instance = (token) => axios.create({ baseURL: `${config.API_URL}`, timeout: 1000, headers :{ 'authorization': 'Bearer ' + token } })
instance.get('/path') .then(response => { return response.data; }) What is path ??
N
Nick Uraltsev

The second parameter of axios.post is data (not config). config is the third parameter. Please see this for details: https://github.com/mzabriskie/axios#axiosposturl-data-config


I
Ilyas karim

By using Axios interceptor:

const service = axios.create({
  timeout: 20000 // request timeout
});

// request interceptor

service.interceptors.request.use(
  config => {
    // Do something before request is sent

    config.headers["Authorization"] = "bearer " + getToken();
    return config;
  },
  error => {
    Promise.reject(error);
  }
);

Is this the community standard for configuring the headers with axios?
@5ervant I had a really ugly time using this approach. It was a lot of pain and I so don't recommend it.
@ankush981 what is so bad about this approach and which one do u recommend?
@NenadKaevik There's a particular use case I was trying to cover (response interception): letting the user know when the server says 403 in response. People generally put the token verification step during component load, but suppose your token was invalidated a few seconds after it was verified (for whatever reason). Now when the person clicks a button, I'd like them to know they've been signed out. It's hard to do this using interceptors as they add global behavior. I got into a reload loop because the request interceptor would always add the token and the response interceptor would redirect
@NenadKaevik So, maybe the flow was hard to achieve or I was using the wrong approach, but since then I kind of started hating interceptors.
N
Neel Patel

If you want to some data after passing token in header so that try this code

const api = 'your api'; 
const token = JSON.parse(sessionStorage.getItem('data'));
const token = user.data.id; /*take only token and save in token variable*/
axios.get(api , { headers: {"Authorization" : `Bearer ${token}`} })
.then(res => {
console.log(res.data);
.catch((error) => {
  console.log(error)
});

g
gdfgdfg

This works and I need to set the token only once in my app.js:

axios.defaults.headers.common = {
    'Authorization': 'Bearer ' + token
};

Then I can make requests in my components without setting the header again.

"axios": "^0.19.0",


I don't know why but with this way it's doesn't work on Safari on iOS device :(
nice simple method for me
H
Hasan Zahran

Just in case someone faced the same issue.

The issue here is when passing the header without data, the header's configuration will be in the payload data, So I needed to pass null instead of data then set the header's configuration.

const config = {
         headers: {
             "Content-type": "application/json",
              "Authorization": `Bearer ${Cookies.get("jwt")}`,
         },
    };    
axios.get(`${BASE_URL}`, null, config)

D
Dinindu Kanchana

I use a separate file to init axios instance and at the same time, I add intercepters to it. Then in each call, the intercepter will add the token to the request header for me.

import axios from 'axios';
import { getToken } from '../hooks/useToken';

const axiosInstance = axios.create({
  baseURL: process.env.REACT_APP_BASE_URL,
});

axiosInstance.interceptors.request.use(
  (config) => {
    const token = getToken();
    const auth = token ? `Bearer ${token}` : '';
    config.headers.common['Authorization'] = auth;
    return config;
  },
  (error) => Promise.reject(error),
);

export default axiosInstance;

Here is how I use it in the service file.

import { CancelToken } from 'axios';
import { ToolResponse } from '../types/Tool';
import axiosInstance from './axios';

export const getTools = (cancelToken: CancelToken): Promise<ToolResponse> => {
  return axiosInstance.get('tool', { cancelToken });
};


Clear solution. can you give ToolResponse file example. Thank you.
M
Mohammed Al-Reai

// usetoken is hook i mad it

export const useToken = () => {
     return JSON.parse(localStorage.getItem('user')).token || ''
}
const token = useToken();



const axiosIntance = axios.create({
    baseURL: api,
    headers: {
        'Authorization':`Bearer ${token}`
    }
});

axiosIntance.interceptors.request.use((req) => {
    if(token){
        req.headers.Authorization = `Bearer ${token}`;
    }
    return req;
})

i
i-codena

If you are sending a post request with empty data remember to always set the second parameter to either empty object or empty string just as in the example below. e.g: axios.post('your-end-point-url-here', '', config)

if you don't set it axios will assume that whatever you are passing as the second parameter is a formData

const config = {
      headers: { Authorization: `Bearer ${storage.getToken()}` }
    };
    axios
      .post('http://localhost:8000/api/v1/get_token_payloads', {}, config)
      .then(({ data: isData }) => {
        console.log(isData);
      })
      .catch(error => {
        console.log(error);
      });

E
Ernesto

axios by itself comes with two useful "methods" the interceptors that are none but middlewares between the request and the response. so if on each request you want to send the token. Use the interceptor.request.

I made apackage that helps you out:

$ npm i axios-es6-class

Now you can use axios as class

export class UserApi extends Api {
    constructor (config) {
        super(config);

        // this middleware is been called right before the http request is made.
        this.interceptors.request.use(param => {
            return {
                ...param,
                defaults: {
                    headers: {
                        ...param.headers,
                        "Authorization": `Bearer ${this.getToken()}`
                    },
                }
            }
        });

      this.login = this.login.bind(this);
      this.getSome = this.getSome.bind(this);
   }

   login (credentials) {
      return this.post("/end-point", {...credentials})
      .then(response => this.setToken(response.data))
      .catch(this.error);
   }


   getSome () {
      return this.get("/end-point")
      .then(this.success)
      .catch(this.error);
   }
}

I mean the implementation of the middleware depends on you, or if you prefer to create your own axios-es6-class https://medium.com/@enetoOlveda/how-to-use-axios-typescript-like-a-pro-7c882f71e34a it is the medium post where it came from


a
afshar003

there are a lot of good solution but I use this

let token=localStorage.getItem("token");

var myAxios=axios.create({
  baseURL: 'https://localhost:5001',
  timeout: 700,
  headers: {'Authorization': `bearer ${token}`}
});

export default myAxios;

then i import myaxios to my file and

myAxios.get("sth")