【问题标题】:how to send axios authorization header in ReactNative?如何在 React Native 中发送 axios 授权标头?
【发布时间】:2018-10-21 07:05:19
【问题描述】:

我添加了一个像

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

          console.log(config);
          return config;
        }

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

【问题讨论】:

    标签: react-native axios


    【解决方案1】:
    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;
            }
    

    【讨论】:

      猜你喜欢
      • 2020-11-21
      • 2020-08-16
      • 2017-10-29
      • 1970-01-01
      • 2018-12-28
      • 2017-11-23
      • 2015-04-25
      • 1970-01-01
      • 2017-05-22
      相关资源
      最近更新 更多