【发布时间】:2019-02-23 16:42:42
【问题描述】:
我在 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 错误。
如果我设置标题如下,我不会得到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',
]
【问题讨论】:
-
尝试使用
application/jsonp而不是application/json——我认为这也可以让你绕过CORS。 -
在附加的 settings.py 中我看不到为 CORS 添加的任何内容,你能指定你添加的内容吗?
标签: javascript python django reactjs