简体   繁体   English

所请求的资源上没有“ Access-Control-Allow-Origin”标头。 [Django反应设置]

[英]No 'Access-Control-Allow-Origin' header is present on the requested resource. [Django-React Setup]

Trying to call a Django API via React. 尝试通过React调用Django API。 But CORS does not seem to be working properly. 但是CORS似乎无法正常工作。

settings.py (django) 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

API in chrome browser, 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
    }
]

React component: 反应组件:

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

Console on running Dashboard on react server 在React Server上运行Dashboard的控制台

Failed to load http://127.0.0.1:8000/products/view : Redirect from ' http://127.0.0.1:8000/products/view ' to ' http://127.0.0.1:8000/products/view/ ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 无法加载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”标头。 Origin ' http://localhost:3000 ' is therefore not allowed access. 因此,不允许访问源' http:// localhost:3000 '。 If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 如果不透明的响应满足您的需求,请将请求的模式设置为“ no-cors”,以在禁用CORS的情况下获取资源。 localhost/:1 Uncaught (in promise) TypeError: Failed to fetch localhost /:1未捕获(承诺)TypeError:无法获取

Edit: Set of response from browser ( http://127.0.0.1:8000/products/view/ ) 编辑:来自浏览器的响应集( 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"
    ]
}

A workaround: 解决方法:

  • Use the chrome extension Allow-Control-Allow-Origin 使用Chrome扩展名Allow-Control-Allow-Origin
  • Use proxy: instead of accessing http://127.0.0.1:8000/products/view , use a proxy like https://cors-anywhere.herokuapp.com/ as a prefix: https://cors-anywhere.herokuapp.com/http://127.0.0.1:8000/products/view 使用代理:不要访问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

暂无
暂无

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

相关问题 **请求的资源上不存在“Access-Control-Allow-Origin”header。** - **No 'Access-Control-Allow-Origin' header is present on the requested resource.** React JS - 请求的资源上不存在“Access-Control-Allow-Origin”header。 跨域资源错误 - React JS - No 'Access-Control-Allow-Origin' header is present on the requested resource. Cross Origin Resource Error 所请求的资源上没有“ Access-Control-Allow-Origin”标头。 -React / Node API - No 'Access-Control-Allow-Origin' header is present on the requested resource. - React/Node API localhost:3000 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”header。 反应和 DJANGO - localhost: 3000 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. REACT and DJANGO React Redux <No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access> - React Redux <No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access> GCP Cloud Function HTTP 触发器“没有'Access-Control-Allow-Origin' header 存在于请求的资源上。” 错误 - GCP Cloud Function HTTP trigger “No 'Access-Control-Allow-Origin' header is present on the requested resource.” error 请求的资源上不存在“Access-Control-Allow-Origin”header。 节点快速获取 - No 'Access-Control-Allow-Origin' header is present on the requested resource. Node Express Fetch 请求的资源上不存在“Access-Control-Allow-Origin”header。 上传不工作 - No 'Access-Control-Allow-Origin' header is present on the requested resource. Uploads are not working ReactJs - NextJs 错误 - (请求的资源上不存在“访问控制允许来源”header。) - ReactJs - NextJs Error - (No 'Access-Control-Allow-Origin' header is present on the requested resource.) 获取 CORS 策略异常:请求的资源上不存在“Access-Control-Allow-Origin”header。 ReactJS/SpringBoot - Getting CORS policy exception: No 'Access-Control-Allow-Origin' header is present on the requested resource. ReactJS/SpringBoot
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM