AJAX的Python Falcon CORS错误

时间:2017-07-19 03:52:45

标签: python ajax cors axios falconframework

我已就此错误阅读了多个SO问题,但似乎没有一个问题可以帮助我解决此问题。 Falcon服务器甚至不打印出print方法的on_post语句(on_get由于某种原因工作正常),不知道我的错误是什么on_post方法。

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

#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');
});

这是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)

我想我在on_post方法中犯了一个小错误,但我不知道它是什么。我会假设至少print语句可以起作用,但事实并非如此。

enter image description here

1 个答案:

答案 0 :(得分:1)

您需要为浏览器发送的CORS preflight OPTIONS request添加处理程序,对吗?

服务器必须回复OPTIONS,其中包含200或204且没有响应正文,并且包含Access-Control-Allow-MethodsAccess-Control-Allow-Headers响应标头。

这样的事情:

def on_options(self, req, res):
    res.status = falcon.HTTP_200
    res.set_header('Access-Control-Allow-Origin', '*')
    res.set_header('Access-Control-Allow-Methods', 'POST')
    res.set_header('Access-Control-Allow-Headers', 'Content-Type')

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

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

pip install falcon-cors

...然后将现有代码更改为:

from falcon_cors import CORS

cors_allow_all = CORS(allow_all_origins=True,
                      allow_all_headers=True,
                      allow_all_methods=True)

api = falcon.API(middleware=[cors.middleware])

#declare resources and instantiate it
class ContactsResource(object):

    cors = cors_allow_all

    def on_get(self, req, res):
        res.status = falcon.HTTP_200
        res.body = ('This is me, Falcon, serving a resource HEY ALL!')
    def on_post(self, req, res):
        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)

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