简体   繁体   English

使用 axios 发送不记名令牌

[英]Sending the bearer token with axios

In my react app i am using axios to perform the REST api requests.在我的反应应用程序中,我使用axios来执行 REST api 请求。

But it's unable to send the Authorization header with the request.但它无法随请求发送授权header。

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.这里validToken()方法将简单地从浏览器存储中返回令牌。

All requests are having a 500 error response saying that所有请求都有一个 500 错误响应,说明

The token could not be parsed from the request无法从请求中解析令牌

from the back-end.从后端。

How to send the authorization header with each requests?如何在每个请求中发送授权 header? Would you recommend any other module with react?你会推荐任何其他带有反应的模块吗?

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.第一个参数是 URL。
The second is the JSON body that will be sent along your request.第二个是将随您的请求发送的 JSON 正文。
The third parameter are the headers (among other things).第三个参数是标题(除其他外)。 Which is JSON as well.这也是 JSON。

Here is a unique way of setting Authorization token in axios.这是在 axios 中设置授权令牌的一种独特方式。 Setting configuration to every axios call is not a good idea and you can change the default Authorization token by:为每个 axios 调用设置配置不是一个好主意,您可以通过以下方式更改默认授权令牌:

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:一些 API 要求将 bearer 写成 Bearer,所以你可以这样做:

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

Now you don't need to set configuration to every API call.现在您不需要为每个 API 调用设置配置。 Now Authorization token is set to every axios call.现在授权令牌设置为每个 axios 调用。

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

The second parameter of axios.post is data (not config ). axios.post的第二个参数是data (不是config )。 config is the third parameter. config是第三个参数。 Please see this for details: https://github.com/mzabriskie/axios#axiosposturl-data-config详情请参阅: https ://github.com/mzabriskie/axios#axiosposturl-data-config

By using Axios interceptor:通过使用 Axios 拦截器:

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

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

This works and I need to set the token only once in my app.js :这有效,我只需要在我的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",

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.这里的问题是当传递没有数据的标头时,标头的配置将在有效负载数据中,所以我需要传递 null 而不是数据,然后设置标头的配置。

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

I use a separate file to init axios instance and at the same time, I add intercepters to it.我使用一个单独的文件来初始化 axios 实例,同时,我向它添加了拦截器。 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 });
};

// usetoken is hook i mad it // 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;
})

You can use interceptors in axios:您可以在 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);
  });

More on that you can find here: https://axios-http.com/docs/interceptors您可以在此处找到更多信息: https://axios-http.com/docs/interceptors

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.如果您要发送带有空数据的发布请求,请记住始终将第二个参数设置为空对象或空字符串,如下例所示。 eg: axios.post('your-end-point-url-here', '', config)例如: 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如果您不设置它,axios 将假定您作为第二个参数传递的任何内容都是 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);
      });

You can try configuring the header like this:您可以尝试像这样配置 header:

const headers = {"Content-Type": "text/plain", "x-access-token": token}

You must mention the 2nd parameter body for the post request even if it is empty, try this:您必须提及发布请求的第二个参数主体,即使它是空的,试试这个:

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

This is what i also faced. 这也是我所面对的。 The token which u are passing is not correct. 你传递的令牌不正确。

Just Hardcode the token and pass, you will get the correct response. 只需对令牌进行硬编码并通过,您将获得正确的响应。 But if token is not passed in single quote '', then it will surely fail. 但如果令牌没有在单引号中传递,那么它肯定会失败。 It must be in format 'Authorization': 'Bearer YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZjN2I1MmI4MDJkNQ', where after Bearer one space must be present, also inside single quotes, this is very important. 它必须采用'授权'格式:'Bearer YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZZNNI1MmI4MDJkNQ',其中必须存在Bearer一个空格后,也在单引号内,这非常重要。

var token = "YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZjN2I1MmI4MDJkNQ";

var headers = {
  Authorization: "Bearer " + token,
  Accept: "application/json, text/plain, */*",
  "Content-Type": "application/json"
};

IMP: The above code will work But if u post something like: IMP:上面的代码可以工作但是如果你发布类似的东西:

'Authorization': 'Bearer '+ YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZjN2I1MmI4MDJkNQ, it will fail '授权':'持票人'+ YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZNNII1MmI4MDJkNQ,它会失败

or-----the below code also will fail, i hope u understand the basic difference 或-----以下代码也将失败,我希望你了解基本的区别

var token = YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjA0YmEzZmZjN2I1MmI4MDJkNQ;

var headers = {
  Authorization: "Bearer " + token,
  Accept: "application/json, text/plain, */*",
  "Content-Type": "application/json"
};

axios by itself comes with two useful "methods" the interceptors that are none but middlewares between the request and the response. axios本身带有两个有用的“方法” interceptors ,它们只是请求和响应之间的中间件。 so if on each request you want to send the token.所以如果你想在每个请求中发送令牌。 Use the interceptor.request .使用interceptor.request

I made apackage that helps you out:我做了一个可以帮助你的包:

$ npm i axios-es6-class

Now you can use axios as 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);
   }
}

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我的意思是middleware的实现取决于你,或者如果你更喜欢创建自己的axios-es6-class https://medium.com/@enetoOlveda/how-to-use-axios-typescript-like-a-pro -7c882f71e34a这是它来自的中型帖子

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 导入我的文件并

myAxios.get("sth")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM