从React JS axios发送请求时未提供身份验证凭证

时间:2020-11-05 13:48:42

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

我正在构建一个简单的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请求的序列化器,但是当我尝试基于函数的视图时,这是第一个没有的序列化器。

响应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;

2 个答案:

答案 0 :(得分: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)
    });
};

答案 1 :(得分:0)

我将描述针对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