【问题标题】:Cross-Origin Resource sharing error: Header Disallowed by preflight response跨域资源共享错误:预检响应不允许标头
【发布时间】:2021-07-18 21:51:45
【问题描述】:

我正在学习如何使用 react 作为前端和 django 作为后端。每次我将 post 方法发送到 django 服务器时,我都会遇到这些 cors 问题。这是一个非常好的应用程序。从 react 发送一个值到 django 服务器并打印它。在 Django 服务器终端中,它显示“OPTIONS /sample HTTP/1.1”200 0 并在反应中显示 cors 错误。我添加了所有不同的类型,但问题仍然存在 enter code here

React Component Code
import axios from 'axios'
import React, { Component } from 'react'
import App from '../App';
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios.defaults.xsrfCookieName = "XCSRF-TOKEN";

class addProduct extends Component {
 constructor(props) {
    super(props)
    this.state  = {
        testId : '12324',
      }

    this.ButtonClicked = this.ButtonClicked.bind(this)
}
ButtonClicked =(e) => {
  e.preventDefault()
  console.log(this.state)
  axios({
        method: 'post',
        url: 'http://127.0.0.1:8000/sample',
        data: this.state.testId,
        crossDomain: true,
        mode : 'CORS',
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET,HEAD,OPTIONS,POST,PUT",
            "Access-Control-Allow-Headers": "Origin, Content-Type",
            "Access-Control-Max-Age" : "200"
          }
        
    })
    .then(Response => console.log(Response.data))
  }

   render() {
    
    return (
        <div className = "addProduct">

            <button  type = "submit" onClick = {this.ButtonClicked} >Start</button>
                   
        </div>
      )
    }
   }

 export default addProduct 



   Django Code:
   from django.shortcuts import render
   from django.http import HttpResponse
   # Create your views here.
  def showsample(request):
     username = request.POST.get('testId')

     print("the value is " ,username)

     return HttpResponse("hello world")

在浏览器网络选项中显示:

请求的网址:http://127.0.0.1:8000/sample 推荐人政策:strict-origin-when-cross-origin

请求标头: 带有警告符号:显示临时标题

接受:application/json、text/plain、/

Access-Control-Allow-Headers:来源、内容类型

访问控制允许来源:*

内容类型:application/x-www-form-urlencoded

引用:http://localhost:4200/ sec-ch-ua: " 非品牌;v="99", "Chromium";v="90", "谷歌浏览器";v="90" sec-ch-ua-mobile: ?0 用户代理:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36

当双击以红色突出显示的“样本”时。

然后post请求通过了,我可以看到Django终端的输出和helloworld的HTTP响应

【问题讨论】:

    标签: python reactjs django cors django-cors-headers


    【解决方案1】:

    经过一番挣扎,我找到了答案。

    我导入了 django.views.decorators.csrf import csrf_exempt 并在 url 模式中添加了这个

    urlpatterns = [

    path('sample', csrf_exempt(views.showsample))
    

    ]

      from django.urls import path
      from django.views.decorators.csrf import csrf_exempt
      from . import views
    
      urlpatterns = [
    
           path('sample', csrf_exempt(views.showsample))
        ]
    

    【讨论】:

      【解决方案2】:

      我在使用 react 和 ajax 时遇到了同样的问题,我尝试通过我的请求传递这些标头,但没有成功,我安装了 Allow CORS chrome 扩展程序,解决了我的问题。

      你的情况我不确定,但试试这两种方法。

      1. 在你的 Django 项目 settings.py 文件中将 ALLOWED_HOSTS 设置为 "*"。像这样:

        ALLOWED_HOSTS = ["*"]

      2. 为 chrome 安装 Allow CORS,或者如果您使用任何其他浏览器,它们也必须有其他与 cors 相关的扩展...

      如果这些都没有帮助,请与我们分享您遇到的错误。

      【讨论】:

        猜你喜欢
        • 2016-11-02
        • 1970-01-01
        • 2011-05-07
        • 2021-05-16
        • 2011-08-14
        • 2013-01-12
        • 2012-05-28
        • 2015-01-08
        • 2018-05-04
        相关资源
        最近更新 更多