简体   繁体   English

向 Django 发出 axios 请求

[英]Making axios request to django

I have a complex problem in sending and receiving data in react to django with axios.在使用 axios 对 django 做出反应时,我在发送和接收数据时遇到了一个复杂的问题。 I'm not using REST API.我没有使用 REST API。 This is my Handel function which is related with my signup form tag and after each click on submit button this function executes:这是我的 Handel 函数,它与我的注册表单标签相关,每次点击提交按钮后,该函数都会执行:

HandelSignUp(e){

e.preventDefault();
let Username = this.refs.username.value;
let Pass = this.refs.pass.value;
let Email =this.refs.email.value;
axios({
  url:'http://127.0.0.1:8000/signupAuth/',
  mothod:'post',
   data:{
    username:this.Username,
    pass:this.Pass,
    email:this.Email
   },
   headers: {
      "X-CSRFToken": window.CSRF_TOKEN,
      "content-type": "application/json"
            }

}).then(respons =>{
  console.log(respons);
})
.catch(err =>{
  console.log(err);
});

and also this is my django urls.py :这也是我的 django urls.py

urlpatterns = [

path('signupAuth/',ReactApp_View.signupRes),

]

ReactApp_View is my views.py in ReactApp file which I imported correctly. ReactApp_View 是我正确导入的 ReactApp 文件中的views.py ok now let's see my views.py :好的,现在让我们看看我的views.py

def signupRes(request):
  body_unicode = request.body.decode('utf-8')
  data = json.loads(myjson)
  return HttpResponse(request.body)

after all when I fill my signup fields and then click on button I see this massage in console log of my browser:毕竟,当我填写注册字段然后单击按钮时,我会在浏览器的控制台日志中看到此消息:

Failed to load http://127.0.0.1:8000/signupAuth/ : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.无法加载http://127.0.0.1:8000/signupAuth/ :对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin ' http://localhost:8000 ' is therefore not allowed access.因此,不允许访问 Origin ' http://localhost:8000 '。

What should I do?我该怎么办?

and an extra question: what happen in the given url in my axios?还有一个额外的问题:我的 axios 中给定的 url 发生了什么?

just open your website with the same host url you are trying to call. 只需使用您要调用的主机网址打开您的网站。 Use http://127.0.0.1:8000/ instead of localhost 使用http://127.0.0.1:8000/代替localhost

You have to allow requests in backend 您必须允许后端请求

CORS_ORIGIN_WHITELIST = (
'http://127.0.0.1:8000',
'http://localhost:8000'
)

or 要么

response["Access-Control-Allow-Origin"] = "*"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM