javascript - 如何在Reactjs中启用CORS?

标签 javascript python django reactjs

我在 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/

相关文章:

python - 保存后维护通过信号填充的模型之间的关系

python - django - "manage.py test"失败 "table already exists"

python - 使用 Django 的 `reverse_lazy` 并将其连接起来

python - 更改 Django ModelChoiceField 以显示用户的全名而不是用户名

javascript - 使用 PHP 在分页中对标题单击进行表排序

javascript - 同位素图像点击显示顶部 div Wordpress 中的新内容

python - 在 Python 中拟合参数曲线

javascript - 使用 focusMode 约束获取所需的媒体设备

javascript - 如何从字符串中删除所有出现的任何给定字符?

python - django - 需要从 list_display 引用另一个模型