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

但是它无法随请求一起发送授权标头。

这是我的代码:

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

无法从请求解析令牌

从后端。

如何发送授权头与每个请求?你会推荐react的其他模块吗?


当前回答

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

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

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

其他回答

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

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

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

通过使用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 headers = {"Content-Type": "text/plain", "x-access-token": token}

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

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

const config = {
         headers: {
             "Content-type": "application/json",
              "Authorization": `Bearer ${Cookies.get("jwt")}`,
         },
    };    
axios.get(`${BASE_URL}`, null, config)
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。