简体   繁体   English

发布到python eve时缺少CORS标头“ Access-Control-Allow-Origin”

[英]CORS header ‘Access-Control-Allow-Origin’ missing when posting to python eve

I have started learning python-eve.I have created the basic demo as shown here : Python eve Quick start" 我已经开始学习python-eve。我已经创建了基本演示,如下所示: Python eve快速入门”

Now I have made a simple web page that will try to post some data to /people on localhost.However when I try to submit the data I get the following error: 现在我做了一个简单的网页,尝试将一些数据发布到localhost上的/ people,但是当我尝试提交数据时,出现以下错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/people . 跨域请求被阻止:同源策略禁止读取位于http:// localhost:5000 / people的远程资源。 (Reason: CORS request did not succeed) (原因:CORS请求未成功)

Here is my html code(the form part): 这是我的html代码(表单部分):

<form action="http://127.0.0.1:5000/people" method="post">
        <div class="form-group">
            <label for="name">First Name</label>
            <input type="text" name="firstname" class="form-control",required>
        </div>
        <div class="form-group">
            <label for="language">Last Name</label>
            <input type="text" name="lastname" class="form-control">
        <button type="submit" class="btn btn-primary btn-lg">Create new Person</button>
    </form>

And here is the javascript code that handles the submit 这是处理提交的javascript代码

!(function(){
    const formSubmit = async function(e){
        const form = this;
        console.log(form)
        e.preventDefault();
        const formData = new FormData(form);
        const serializedData = JSON.stringify(formData);
        const options = {
            headers: {
                'Access-Control-Allow-Origin': '*',
            },
            body:serializedData,
            data:serializedData
        };

        try{
            const url = 'http://localhost:5000/people';
            options.url = url;
            $.post(options, {
                success: (e) => {
                    console.log('success', e)
                },
                error: (e) => console.log('error', e)});
        }catch(e){
            console.log('Oh crap.Something happened');
            console.log(e);
        }
    };
    document.addEventListener('DOMContentLoaded',function(){
        const form = document.querySelector('form');
        form.addEventListener('submit',formSubmit);
    });
}());

Any ideas how can I solve it?I open this page using Webstorm. 有什么解决办法吗?我使用Webstorm打开此页面。

The sollutions provided by node won't work for my case I have added X_DOMAINS='*' to settings.py but still getting the same error 在我为X.DOMAINS ='*'添加到settings.py的情况下,node提供的解决方案不起作用,但仍然出现相同的错误

Here is settings.py : 这是settings.py

MONGO_HOST = 'localhost'
MONGO_PORT = 27019
MONGO_DBNAME = 'apitest'
RATE_LIMIT_REQUEST = (2,60)
X_DOMAINS='*'
pschema = {
    'firstname': {
        'type': 'string',
        'minlength': 1,
        'maxlength': 10
    },
    'lastname': {
        'type': 'string',
        'minlength': 1,
        'maxlength': 10
    },
    'role': {
        'type': 'list',
        'allowed': ["author", "contributor", "copy"],
    },
    # An embedded 'strongly-typed' dictionary.
    'location': {
        'type': 'dict',
        'schema': {
            'address': {'type': 'string'},
            'city': {'type': 'string'}
        },
    },
    'born': {
        'type': 'datetime',
    },
}
aschema = {
    'name': {
        'type': 'string'
    },
    'language': {
        'type': 'string'
    }
}
people = {
    # 'title' tag used in item links. Defaults to the resource title minus
    # the final, plural 's' (works fine in most cases but not for 'people')
    'item_title': 'person',

    # by default the standard item entry point is defined as
    # '/people/<ObjectId>'. We leave it untouched, and we also enable an
    # additional read-only entry point. This way consumers can also perform
    # GET requests at '/people/<lastname>'.
    'additional_lookup': {
        'url': 'regex("[\w]+")',
        'field': 'lastname'
    },

    # We choose to override global cache-control directives for this resource.
    'cache_control': 'max-age=10,must-revalidate',
    'cache_expires': 10,

    # most global settings can be overridden at resource level
    'resource_methods': ['GET', 'POST'],

    'schema': pschema
}


assingments = {
    'item_title': 'assingment',
    # We choose to override global cache-control directives for this resource.
    'cache_control': 'max-age=10,must-revalidate',
    'cache_expires': 10,

    # most global settings can be overridden at resource level
    'resource_methods': ['GET', 'POST'],

    'schema': aschema
}

DOMAIN = {
    'people': people,
    'assingments': assingments
}

The headers need to be set. 标头需要设置。 This is how its done in python tornado. 这是在python龙卷风中完成的方式。 You could maybe look up how to do this in eve. 您也许可以在前夕查找如何执行此操作。

def set_default_headers(self):
    self.set_header("Access-Control-Allow-Origin", "*")
    self.set_header("Access-Control-Allow-Headers", "x-requested-with")
    self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')

I had the exact same problem. 我有同样的问题。 Your form says: 您的表格说:

<form action="http://127.0.0.1:5000/people" method="post">

Your callback says: 您的回叫说:

try{
            const url = 'http://localhost:5000/people';
            options.url = url;

127.0.0.1 and localhost are not the same thing to JQuery and it rejects the response as a cross-site scripting error. 127.0.0.1和localhost与JQuery不同,它拒绝响应作为跨站点脚本错误。

Hey I finally found a solution to my problem.I just need to use @app.after_request like this: 嘿,我终于找到了解决我问题的方法,我只需要像这样使用@ app.after_request:

@app.after_request
def after_request(response):
  response.headers.set('Access-Control-Allow-Origin', '*')
  response.headers.set('Access-Control-Allow-Headers', 'Content-Type,Authorization')
  response.headers.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
  return response 

This will take care of any cors errors 这将解决任何cors错误

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM