首页 > 解决方案 > django 和 axios:如何为 OPTIONS 启用 CORS

问题描述

我正在使用 axiosPOST在我的 reactjs 页面中执行请求。

  const url = "test/";
  const data = {
    email: "test@test.com",
    password: "test",
  };
  const headers = {
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
  };

  axios.post(url, data, headers)
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  })

在我的 Django 中,我有

CORS_ALLOW_ALL_ORIGINS =  True

我的 axios 请求工作正常。

但是现在在我的 Django 视图(对应于 url)中,我故意放了一个错误的 python 语句。

IE

def test(request):
   a+=1
   ..... return some json

**如果我不放 a+=1 那么 axios 工作正常,没有任何错误

当运行 axios 代码时,我得到

在此处输入图像描述

并且

在此处输入图像描述

在我的 Django 控制台中,我看到:

Traceback (most recent call last):
.........
  ........../views.py", line 139, in test
    a+=1
NameError: name 'a' is not defined

但一般来说,如果我不使用 rest api,当浏览器本身发生任何错误时,Django 会显示回溯 html。

即使使用 ajax,我也可以在 developertools 中看到响应。

但是使用 axios 它没有显示

我检查了邮递员它显示了回溯

在此处输入图像描述

有人可以帮助如何实现这一目标。我也想在脚本中捕获回溯

标签: reactjsdjangoaxios

解决方案


推荐阅读