请求的资源上不存在“Access-Control-Allow-Origin”标头。 [Django-React设置]

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了请求的资源上不存在“Access-Control-Allow-Origin”标头。 [Django-React设置]相关的知识,希望对你有一定的参考价值。

试图通过React调用Django API。但CORS似乎没有正常工作。

settings.py(django)

ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'oauth2_provider',
    'rest_framework',
    'accounts',
    'products',
    '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',
    'oauth2_provider.middleware.OAuth2TokenMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True

Chrome浏览器中的API,

GET /products/view/
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {
        "id": 5,
        "name": "product_updated",
        "image": "...",
        "cost": "50.00",
        "avail_quantity": 100,
        "desc": "Good",
        "rating": "3.60",
        "users_rated": 100
    },
    {
        "id": 14,
        "name": "Dark Coffee",
        "image": "...",
        "cost": "50.00",
        "avail_quantity": 100,
        "desc": "Good",
        "rating": "3.60",
        "users_rated": 100
    }
]

反应组件:

import React, { Component } from 'react'

class Dashboard extends Component {

  constructor(props) {
    super(props)
    this.state = {
      text: '127.0.0.1:8000',
      productList: []
    }
     this.fetchProducts = this.fetchProducts.bind(this)
  }

 fetchProducts(){
     fetch(`http://127.0.0.1:8000/products/view`, {
         method: "GET",
          }).then(res=> res.json())
            .then(res=> {
              console.log(res, typeof res, res.length)
            this.setState({productList: res})
          })
      console.log(this.state.productList)
}


 componentWillMount(){
    this.fetchProducts()
 }

render() {
  var list = []
  for (let i = this.state.productList.length-1; i >= 0; i--) {
        list.push(<li>{this.state.productList[i].name}</li>)
        console.log(list)
      }
  return (
    <div className="dashboard">

    <h1>Welcome To Bear State Coffee!</h1>
    <h3>Products: </h3>
    <ul>
      {list}
    </ul>

    </div>
  )
}
}

export default Dashboard

在反应服务器上运行仪表板的控制台

无法加载http://127.0.0.1:8000/products/view:从'http://127.0.0.1:8000/products/view'重定向到'http://127.0.0.1:8000/products/view/'已被CORS策略阻止:请求的资源上没有'Access-Control-Allow-Origin'标头。因此,'http://localhost:3000'原产地不允许进入。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用CORS的资源。 localhost /:1 Uncaught(在promise中)TypeError:无法获取

编辑:来自浏览器的响应集(http://127.0.0.1:8000/products/view/

OPTIONS /products/view/
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "name": "Products",
    "description": "GET: For viewing all products",
    "renders": [
        "application/json",
        "text/html"
    ],
    "parses": [
        "application/json",
        "application/x-www-form-urlencoded",
        "multipart/form-data"
    ]
}
答案

解决方法:

  • 使用镀铬扩展Allow-Control-Allow-Origin
  • 使用代理:而不是访问http://127.0.0.1:8000/products/view,使用像https://cors-anywhere.herokuapp.com/这样的代理作为前缀:https://cors-anywhere.herokuapp.com/http://127.0.0.1:8000/products/view

以上是关于请求的资源上不存在“Access-Control-Allow-Origin”标头。 [Django-React设置]的主要内容,如果未能解决你的问题,请参考以下文章

django中的“请求的资源上不存在'Access-Control-Allow-Origin'标头”

如何解决请求的资源上不存在“Access-Control-Allow-Origin”标头

Http.post 请求的资源上不存在“Access-Control-Allow-Origin”标头

请求的资源发布请求上不存在“Access-Control-Allow-Origin”标头

Angular 2请求的资源上不存在“Access-Control-Allow-Origin”标头[重复]

API 请求错误 - 请求的资源上不存在“Access-Control-Allow-Origin”标头