gpt4 book ai didi

javascript - 如何在Reactjs中启用CORS?

转载 作者:行者123 更新时间:2023-12-03 00:08:53 26 4
gpt4 key购买 nike

我在 React.js 中使用这个 fetchData 配置:

fetchData = () => {
fetch("http://localhost:8000/batch_predict", {
method: "POST",
headers: {
'Accept': 'application/json, text/plain, */*',
//'Content-Type': 'application/json'
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" // otherwise $_POST is empty
},
,
body: JSON.stringify({
holdingTime: this.state.holdingTime,
csvData: this.state.csvData
})
})
.then((resp) => {
return resp.json()
})
.then((data) => {
this.updateDelay(data.prediction)
})
.catch((error) => {
console.log(error, "catch the hoop")
})

};

它发送的数据很好,但是我收到 CORS 错误。

如果我按如下方式设置 header ,则不会收到 CORS 错误,但数据设置错误:

 headers: {
"Content-Type": "application/json; charset=utf-8",
}

因此我想保留第一个选项,但是在这种情况下如何启用 CORS?

在 Django 后端 settings.py 中,我添加了所有与 CORS 相关的行:

ALLOWED_HOSTS = ["*"]


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

最佳答案

在 OPTION 请求中,服务器应指示它实际上允许跨站点请求,但期望发送凭据。这是通过 Access-Control-Allow-Credentials: true 响应 header 完成的,可以使用 djang-cors-headers 包进行设置。

pip3 install django-cors-headers

设置.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_WHITELIST = (
'localhost:3000',
)

引用:https://medium.com/@zoltankohalmy/react-and-django-57f949b0f012

关于javascript - 如何在Reactjs中启用CORS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54843747/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com