如何在ReactNative中发送axios授权标头?

时间:2018-10-21 07:05:20

标签: react-native axios

我添加了

这样的拦截器
function ({getState, dispatch, getSourceAction}, config) {
          AsyncStorage.getItem("userToken").then((value) => {
              config.headers.Authorization = `Bearer ${value}`;
          })

          console.log(config);
          return config;
        }

我可以在控制台中看到授权标头,但是我的服务器没有收到它。

enter image description here

1 个答案:

答案 0 :(得分:0)

const headers = {
  Accept: 'application/json',
  'Content-Type': 'application/json',
};

const URL = 'yourUrl';

const makeAuthenticatedApiCall = ({
  method = 'get',
  path,
  data,
  customHeaders = {},
}) => {
  console.log(`Calling ${method}`, `${URL}${path}`);
  return axios({
    url: `${URL}${path}`,
    method,
    headers: {
      ...headers,
      ...customHeaders
    },
    data,
  });
};


// and make a call like this:
AsyncStorage.getItem("userToken").then((value) => {

   makeAuthenticatedApiCall({
          method: 'put',
          path: '/resourcePathToBeAddedHere',
          {someData: {}},
          customHeaders: { Authorization: `Bearer ${value};` },
        }));
});

我认为您代码中的问题在于,您正在将授权标头设置为一个在返回之前就可以解析的承诺中:

function ({getState, dispatch, getSourceAction}, config) {
          AsyncStorage.getItem("userToken").then((value) => {
              config.headers.Authorization = `Bearer ${value}`; //<--this is set too late, the return is already done at this point.
          })

          console.log(config);
          return config;
        }