【发布时间】: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