簡體   English   中英

從 React JS axios 發送請求時未提供身份驗證憑據

[英]Authentication credentials were not provided when sending request from React JS axios

我正在構建一個簡單的 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)

這是我從郵遞員發送請求時得到的 -

{'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;

如果您不想傳遞數據,請嘗試類似的操作

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

我將描述我的 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 應用程序的完整教程。 您可以閱讀有關 React to Django backend 中登錄功能文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM