【问题标题】:Authentication credentials were not provided when sending request from React JS axios从 React JS axios 发送请求时未提供身份验证凭据
【发布时间】:2021-02-18 05:43:38
【问题描述】:

我正在构建一个简单的 API,但现在我遇到了一些后端问题。我一直使用 Django-rest-framework 序列化程序,但现在我正在尝试编写基于函数的视图。我的后端服务器默认使用 knox 令牌身份验证,我在 Django 设置中进行了设置(如下)

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES':
    ('knox.auth.TokenAuthentication', )
}

所以问题是当邮递员发送POST请求时,服务器会识别调用请求的用户,但是当从React JS发送请求时,服务器找不到用户。

这是我的views.py 基于函数的视图:

@csrf_exempt
@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
def hello_world(request):
    print(request.data)
    print(request.headers)
    print('user', request.user.username)

这是我从 POSTMAN 发送请求时得到的 -

{'report': 'testas'}
{'Content-Length': '28', 'Content-Type': 'application/json', 'Authorization': 'Token 024f51b3f210082302ceb1fff29eff3fcefd50437c6909ca7d6647a1ce1d66bb', 'User-Agent': 'PostmanRuntime/7.26.8', 'Accept': '*/*', 'Postman-Token': '5e9be4f1-cbf5-4f8f-bf7c-f44761c30798', 'Host': '192.168.0.30:8000', 'Accept-Encoding': 'gzip, deflate, br', 'Connection': 'keep-alive'}
user 3nematix

这来自 React JS:

{'headers': {'Content-Type': 'application/json', 'Authorization': 'Token d8bce38c58d07ade11446147cab60ac7795813232cc44d93e9d0da46bd16384e'}}
{'Content-Length': '136', 'Content-Type': 'application/json;charset=UTF-8', 'Host': '192.168.0.30:8000', 'Connection': 'keep-alive', 'Accept': 'application/json, text/plain, */*', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36', 'Origin': 'http://192.168.0.30:8000', 'Referer': 'http://192.168.0.30:8000/reports/view', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9'}
user

我该如何解决这个问题?我有其他识别 React JS 请求的序列化程序,但是当我尝试基于函数的视图时,这是第一个没有。

React JS Axios API 调用:

import axios from 'axios';
import tokenConfig from './auth';

// Like Report
export const likePostas = (report_public_id) => (dispatch, getState) => {
  axios
    .post(`/api/report/like?report=${report_public_id}`, tokenConfig(getState))
    .then((res) => {
      console.log(res.data)
    })
    .catch(err => {
      console.log(err.response.data)
    });
};

tokenConfig 函数:

// Setup config with token - helper function
export const tokenConfig = (getState) => {
  // Get token from state
  const token = getState().auth.token;

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

  // If token, add to headers config
  if (token) {
    config.headers['Authorization'] = `Token ${token}`;
  }

  return config;
};

export default tokenConfig;

【问题讨论】:

  • 首先在post中需要2个字段,第一个是URL,第二个是数据,然后你可以使用标题,什么是tokenConfig?
  • 我已经用 tokenConfig 函数更新了问题
  • 是get request还是post?
  • 这是发布请求
  • .post(/api/report/like?report=${report_public_id}, {}, tokenConfig(getState)) 如果您不想传递数据,请尝试类似的方法

标签: javascript reactjs django django-rest-framework django-react


【解决方案1】:

如果您不想传递数据,请尝试类似的方法

import axios from 'axios';
import tokenConfig from './auth';

// Like Report
export const likePostas = (report_public_id) => (dispatch, getState) => {
  axios
    .post(`/api/report/like?report=${report_public_id}`, {}, tokenConfig(getState))
    .then((res) => {
      console.log(res.data)
    })
    .catch(err => {
      console.log(err.response.data)
    });
};

【讨论】:

    【解决方案2】:

    我将描述我对 Django+React 应用程序的方法。当我从服务器获取令牌时,我将其设置为 axios 默认值,所以我不需要记得添加它:

    export const setAxiosAuthToken = token => {
      if (typeof token !== "undefined" && token) {
        // Apply for every request
        axios.defaults.headers.common["Authorization"] = "Token " + token;
      } else {
        // Delete auth header
        delete axios.defaults.headers.common["Authorization"];
      }
    };
    

    如果您注销,则只需使用空字符串作为令牌调用上述函数。

    我正在编写如何使用 Django+React 从头开始​​编写 SaaS 应用程序的完整教程。您可以阅读article about login feature in React to Django backend。

    【讨论】:

      猜你喜欢
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 2020-03-11
      • 2018-11-28
      • 2020-07-22
      • 2019-04-26
      • 2020-01-11
      • 2019-07-29
      相关资源
      最近更新 更多