无法将 JWT header 设置为 axios

Unable to set JWT header to axios

我有 Django REST 作为后端。我需要通过 GET.
查询数据库 问题:
Header 不在 GET 方法中。因此 Django returns 我 "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

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

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);
  });

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

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

在我的应用程序中,我完成了如下工作 首先我创建一个名为 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;