如何在Reactjs中启用CORS?

2024-09-30 01:19:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我在中使用这个fetchData配置React.js公司公司名称:

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错误,但数据设置错误:

^{pr2}$

因此,我想保留第一个选项,但是在这种情况下,如何启用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',
]

Tags: djangojsonapplicationtype错误公司contentthis

热门问题