Python Falcon CORS 与 AJAX 错误

qar*_*dso 3 python ajax cors falconframework axios

我已经阅读了有关此错误的多个 SO 问题,但它们似乎都没有帮助我解决此问题。Falcon 服务器甚至没有打印出printon_post方法的语句(on_get由于某种原因工作正常),不确定我的on_post方法有什么问题。


我正在调用我的 post 方法localhost:8000

#client side
var ax = axios.create({
    baseURL: 'http://localhost:5000/api/',
    timeout: 2000,
    headers: {}
});

ax.post('/contacts', {
    firstName: 'Kelly',
    lastName: 'Rowland',
    zipCode: '88293'
}).then(function(data) {
    console.log(data.data);
}).catch(function(err){
    console.log('This is the catch statement');
});
Run Code Online (Sandbox Code Playgroud)

这是 Falcon 服务器代码

import falcon
from peewee import *


#declare resources and instantiate it
class ContactsResource(object):
    def on_get(self, req, res):
        res.status = falcon.HTTP_200
        res.body = ('This is me, Falcon, serving a resource HEY ALL!')
        res.set_header('Access-Control-Allow-Origin', '*')
    def on_post(self, req, res):
        res.set_header('Access-Control-Allow-Origin', '*')
        print('hey everyone')
        print(req.context)
        res.status = falcon.HTTP_201
        res.body = ('posted up')

contacts_resource = ContactsResource()

app = falcon.API()

app.add_route('/api/contacts', contacts_resource)
Run Code Online (Sandbox Code Playgroud)

我想我的on_post方法犯了一个小错误,但我不知道它是什么。我本以为至少这些print陈述会起作用,但事实并非如此。

在此输入图像描述

sid*_*ker 5

您需要为浏览器发送的CORS 预检OPTIONS请求添加处理程序,对吧?

\n

服务器必须OPTIONS使用 200 或 204 响应,并且不包含响应正文,并包含Access-Control-Allow-MethodsAccess-Control-Allow-Headers响应标头。

\n

所以像这样:

\n
def on_options(self, req, res):\n    res.status = falcon.HTTP_200\n    res.set_header(\'Access-Control-Allow-Origin\', \'*\')\n    res.set_header(\'Access-Control-Allow-Methods\', \'POST\')\n    res.set_header(\'Access-Control-Allow-Headers\', \'Content-Type\')\n
Run Code Online (Sandbox Code Playgroud)\n

将值调整Access-Control-Allow-Headers为您实际需要的值。

\n

或者您可以使用该falcon-cors包:

\n
pip install falcon-cors\n
Run Code Online (Sandbox Code Playgroud)\n

\xe2\x80\xa6然后将现有代码更改为:

\n
from falcon_cors import CORS\n\ncors_allow_all = CORS(allow_all_origins=True,\n                      allow_all_headers=True,\n                      allow_all_methods=True)\n\napp = falcon.API(middleware=[cors.middleware])\n\n#declare resources and instantiate it\nclass ContactsResource(object):\n\n    cors = cors_allow_all\n\n    def on_get(self, req, res):\n        res.status = falcon.HTTP_200\n        res.body = (\'This is me, Falcon, serving a resource HEY ALL!\')\n    def on_post(self, req, res):\n        print(\'hey everyone\')\n        print(req.context)\n        res.status = falcon.HTTP_201\n        res.body = (\'posted up\')\n\ncontacts_resource = ContactsResource()\n\napp.add_route(\'/api/contacts\', contacts_resource)\n
Run Code Online (Sandbox Code Playgroud)\n

您可能还需要设置该allow_credentials_all_origins=True选项。

\n