在我的react应用程序中,我使用axios来执行REST api请求。

但是它无法随请求一起发送授权标头。

这是我的代码:

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

这里,validToken()方法将简单地从浏览器存储中返回令牌。

所有的请求都有一个500错误响应

无法从请求解析令牌

从后端。

如何发送授权头与每个请求?你会推荐react的其他模块吗?


当前回答

Axios本身带有两个有用的“方法”——拦截器,它们只是请求和响应之间的中间件。如果每个请求都要发送令牌。使用interceptor.request。

我做了一个包来帮助你:

$ npm i axios-es6-class

现在可以使用axios作为类了

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);
   }
}

我的意思是中间件的实现取决于您,或者如果您喜欢创建自己的axios-es6-class https://medium.com/@enetoOlveda/how-to-use-axios-typescript-like-a-pro-7c882f71e34a 这是它来自的中帖

其他回答

您可以一次创建配置,然后在任何地方使用它。

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

instance.get('/path')
.then(response => {
    return response.data;
})
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);

第一个参数是URL。 第二个是随请求发送的JSON主体。 第三个参数是头(以及其他内容)。这也是JSON。

如果你想在头中传递令牌后的一些数据,那么试试这段代码

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)
});

你可以在axios中使用拦截器:


axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

更多信息可以在这里找到:https://axios-http.com/docs/interceptors

// usetoken是钩子我疯了它

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;
})