繁体   English   中英

使用 axios 发送不记名令牌

[英]Sending the bearer token with axios

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

但它无法随请求发送授权header。

这是我的代码:

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 错误响应,说明

无法从请求中解析令牌

从后端。

如何在每个请求中发送授权 header? 你会推荐任何其他带有反应的模块吗?

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。

这是在 axios 中设置授权令牌的一种独特方式。 为每个 axios 调用设置配置不是一个好主意,您可以通过以下方式更改默认授权令牌:

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

一些 API 要求将 bearer 写成 Bearer,所以你可以这样做:

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

现在您不需要为每个 API 调用设置配置。 现在授权令牌设置为每个 axios 调用。

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

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

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

axios.post的第二个参数是data (不是config )。 config是第三个参数。 详情请参阅: https ://github.com/mzabriskie/axios#axiosposturl-data-config

通过使用 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);
  }
);

如果您想在标头中传递令牌后获取一些数据,请尝试此代码

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

这有效,我只需要在我的app.js中设置一次令牌:

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

然后我可以在我的组件中发出请求,而无需再次设置标头。

"axios": "^0.19.0",

以防万一有人遇到同样的问题。

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

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

我使用一个单独的文件来初始化 axios 实例,同时,我向它添加了拦截器。 然后在每次调用中,拦截器都会为我将令牌添加到请求标头中。

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;

这是我在服务文件中使用它的方式。

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 是钩子,我疯了

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

您可以在 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

如果您要发送带有空数据的发布请求,请记住始终将第二个参数设置为空对象或空字符串,如下例所示。 例如: axios.post('your-end-point-url-here', '', config)

如果您不设置它,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);
      });

您可以尝试像这样配置 header:

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

您必须提及发布请求的第二个参数主体,即使它是空的,试试这个:

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

这也是我所面对的。 你传递的令牌不正确。

只需对令牌进行硬编码并通过,您将获得正确的响应。 但如果令牌没有在单引号中传递,那么它肯定会失败。 它必须采用'授权'格式:'Bearer YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZZNNI1MmI4MDJkNQ',其中必须存在Bearer一个空格后,也在单引号内,这非常重要。

var token = "YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZjN2I1MmI4MDJkNQ";

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

IMP:上面的代码可以工作但是如果你发布类似的东西:

'授权':'持票人'+ YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZNNII1MmI4MDJkNQ,它会失败

或-----以下代码也将失败,我希望你了解基本的区别

var token = YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjA0YmEzZmZjN2I1MmI4MDJkNQ;

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

axios本身带有两个有用的“方法” interceptors ,它们只是请求和响应之间的中间件。 所以如果你想在每个请求中发送令牌。 使用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);
   }
}

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

有很多好的解决方案,但我用这个

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

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

export default myAxios;

然后我将 myaxios 导入我的文件并

myAxios.get("sth")

暂无
暂无

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

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