【问题标题】:Add Bearer type header in react native axios在 react native axios 中添加 Bearer 类型标头
【发布时间】:2020-11-07 09:37:23
【问题描述】:

我正在使用 react native axios 并尝试添加 Bearer 的标头类型。

它在邮递员中工作得很好:-

但它在我的代码中不起作用。 我的代码是:-

const axiosInstance = axios.create ({
 //baseURL: process.env.VUE_APP_ROOT_API,
  //timeout: 1000,
  headers: {'Content-Type': 'application/json'},
 });


axiosInstance.interceptors.request.use (
async function(config) {
console.log('config', config);
const token = await getUserAccessTokenFromStorage();
console.log('token in axios get',token);

if (token) config.headers.common = {'token': `Bearer ${token}`}; //try1
//if (token) config.headers.token = `Bearer ${token}`; //try2
return config;
 },
function (error) {
return Promise.reject (error);
 }
 );

export const GET = async (url, params) => {
let getRes = await axiosInstance.get(
url,
params
);
if (getRes.status === 200) {
return {data: getRes.data, status: true};
 } else {
return {message: getRes.data.message, status: false};
}
};

我能做些什么来解决这个问题?

谢谢!!!

【问题讨论】:

    标签: javascript reactjs react-native react-redux axios


    【解决方案1】:

    您没有从 if 子句返回 config。这段代码应该可以工作。

    axiosInstance.interceptors.request.use(
      async function(config) {
        console.log("config", config);
        const token = await getUserAccessTokenFromStorage();
        console.log("token in axios get", token);
    
        if (token) {
          return {
            ...config,
            headers: {
              ...config.headers,
              token: `Bearer ${token}`
    
            }
          };
        }
    
        return config;
      },
      function(error) {
        return Promise.reject(error);
      }
    );
    

    PS:您应该使用Authorization: Bearer <token> 标头用于此类目的。

    【讨论】:

    • 谢谢,将令牌更改为授权后,它可以工作了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多