我使用React.js 16.8,Falcon Python Framework 1.4.1和peewee ORM 3.9.3构建了简单的SPA。
create-react-app
(最新的CLI)命令创建的。这是我的./api/__init__.py
:
import falcon
from falcon_cors import CORS
from api.views import UserResource
cors = CORS(
allow_all_origins=True,
allow_credentials_all_origins=True,
allow_all_headers=True,
log_level='DEBUG'
)
# Init app
app = falcon.API(middleware=[cors.middleware])
# API routes
app.add_route('/api/user', UserResource())
...我的./api/views.py
是:
import json
from falcon import HTTP_404
from playhouse.shortcuts import model_to_dict
from api.models import Users
from api.utils import str_converter
class UserResource(object):
"""
User endpoint
Methods: GET
"""
# Show User by ID
def on_get(self, req, resp):
try:
# Build user query
user = Users.get(Users.id == req.media.get('id'))
# Return JSON with user object
resp.body = json.dumps({
"data": model_to_dict(user),
"status": "success",
"description": None
}, default=str_converter)
except Users.DoesNotExist:
# Return JSON with error (404)
resp.status = HTTP_404
resp.body = json.dumps({
"data": None,
"status": "error",
"description": "User does not exists!"
})
./frontend/src/App.js
:
import React, {Component} from 'react';
import axios from 'axios';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
users: []
};
}
componentDidMount() {
axios.get('http://127.0.0.1:8000/api/user', {
data: {
id: 1
}
}).then(
(result) => {
this.setState({
isLoaded: true,
users: result.data.data
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
});
}
render() {
const {error, isLoaded, users} = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="App">
<ul>
{users.map(user => (<li key={user.uuid}>{user.first_name} {user.last_name}</li>))}
</ul>
</div>
);
}
}
};
当我运行此应用程序(正面和背面)时:
$ gunicorn --reload api:app # --> http://127.0.0.1:8000
$ npm start # --> http://localhost:3000
在Google Chrome控制台上,我看到此错误:
CORS策略已阻止从源“ http://127.0.0.1:8000/api/user”访问“ http://localhost:3000”处的XMLHttpRequest:在飞行前响应中,Access-Control-Allow-Headers不允许请求标头字段内容类型
当我在浏览器上刷新log_level='DEBUG'
页面时,Falcon CORS localhost:3000
向我展示:
由于不允许的方法而中止响应
为什么?我做错了什么方式?