试图通过调用反应的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政策:否‘访问控制允许来源’标头出现在所请求的资源。 原产地“ 的http://本地主机:3000 ”因此不允许访问。 如果一个不透明的响应提供您的需求,设置请求的模式,以“无CORS”获取禁用CORS的资源。 本地主机/:1未捕获(在承诺)类型错误:无法抓取
编辑:设置从浏览器的响应( 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"
]
}