简体   繁体   English

如何在Reactjs中启用CORS?

[英]How to enable CORS in Reactjs?

I use this fetchData config in React.js: 我在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")
  })

}; };

It sends well the data, however I get CORS error. 它很好地发送了数据,但是出现了CORS错误。

If I set headers as follows, I do not get CORS error, but the data is set wrongly: 如果按以下方式设置标题,则不会出现CORS错误,但是数据设置错误:

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

Therefore I want to maintain the first option, but how can I enable CORS in this case? 因此,我想保留第一个选项,但是在这种情况下如何启用CORS?

In Django backend settings.py I added all the CORS related lines: 在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',
]

In the OPTION request the server should indicate, that it actually allows cross site requests but expects credentials to be sent. 服务器应该在OPTION请求中指出,它实际上允许跨站点请求,但希望发送凭据。 This is done by the Access-Control-Allow-Credentials: true response header which can be set up by using the djang-cors-headers package. 这是通过Access-Control-Allow-Credentials:真正的响应标头完成的,可以使用djang-cors-headers包进行设置。

pip3 install django-cors-headers

settings.py settings.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',
)

Reference: https://medium.com/@zoltankohalmy/react-and-django-57f949b0f012 参考: https : //medium.com/@zoltankohalmy/react-and-django-57f949b0f012

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

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