无法将JWT标头设置为axios

时间:2017-12-11 10:48:14

标签: javascript reactjs axios

我将Django REST作为后端。我需要通过GET查询数据库 的问题:
标头不在GET方法中。所以Django回报了我 "Authentication credentials were not provided."

问题:
我哪里错了?

export function fetchCompanies(token, callback) {
  const instance = axios.create({
    baseURL: `${ROOT_URL}`,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'jwt '.concat(token)
    }
    // headers: `{content-type=application/json&authorization='+${jwtReady}}`
    // headers: JSON.stringify(
    //   {'Content-Type':'application/json','Authorization': jwtReady}
    // )
  });

  const request = instance.get('/api/companies/')
    .then((res) => {
      console.log(res);
      callback(res);
    })
    .catch((err) => {
      console.log(err);
      callback(err.response);
    });
  return{
    type: FETCH_COMPANIES,
    payload: request
  }
}

参考文献:
https://github.com/axios/axios#axiosgeturl-config

Postman App

3 个答案:

答案 0 :(得分:1)

我遇到了同样的问题。不知道如何正确修复它,但我已将代码更改为:

var jwtReady = 'jwt '.concat(token);
...
headers: {'content-type=application/json&authorization='+jwtReady}

您也可以尝试使用

JSON.stringify({'Content-Type':'application/json','Authorization': 'jwt '.concat(token)}


修改
试着这样写:

const querystring = require('querystring');

const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'jwt '.concat(token)
}

axios({
  method: 'get',
  url: `${ROOT_URL}/api/companies/`,
  headers: querystring.stringify(headers)
})
  .then((res) => {
    console.log(res);
    callback(res);
  })
  .catch((err) => {
    console.log(err);
    callback(err.response);
  });

答案 1 :(得分:1)

在我的申请表中,我完成了以下工作 首先我创建一个名为AxiosConfig.js的文件,代码是这样的,这个函数读取我存储在本地存储中的jwt并将其设置在axios config

/**
 * this file contains configuration for Axios Library
 */
 import axios from 'axios'

 const AxiosConfig = (config = axios.defaults) =>{
    if(localStorage.getItem('jwtToken')){
    config.headers.authorization = `Bearer ${localStorage.getItem('jwtToken')}`
   }
return config;
  }
export default AxiosConfig;

现在我创建了另一个用于调用的文件:

import axios from "axios";
import axiosConfig from "./AxiosConfig";
 const headers = {};
 class AppsAPI {
 static getAllApps(userId) {
   return axios
    .post("someurl", {}, axiosConfig()) //===> Here i set axios config
  .then(res => res.data)
  .catch(err => console.log(err));
  }
}
export default AppsAPI;

答案 2 :(得分:0)

我必须安装这个东西。问题来自后端。 在没有token的情况下,我被误导为POSTheaders 这对登录机制来说很好。虽然我的配置是正确的,但实际上当reactjs/redux gitter频道的@panigrap再次向我提及时。

https://github.com/ottoyiu/django-cors-headers/