javascript - 发布到 python eve 时缺少 CORS header ‘Access-Control-Allow-Origin’

标签 javascript python cors eve

我已经开始学习 python-eve。我已经创建了基本演示,如下所示:Python eve Quick start"

现在我制作了一个简单的网页,它将尝试将一些数据发布到本地主机上的/people 。但是,当我尝试提交数据时,出现以下错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/people. (Reason: CORS request did not succeed)

这是我的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>

这是处理提交的 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);
    });
}());

有什么办法可以解决这个问题吗?我使用 Webstorm 打开此页面。

节点提供的解决方案不适用于我的情况 我已将 X_DOMAINS='*' 添加到 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
}

最佳答案

嘿,我终于找到了解决问题的方法。我只需要像这样使用@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 

这将解决任何 cors 错误

关于javascript - 发布到 python eve 时缺少 CORS header ‘Access-Control-Allow-Origin’,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52279068/

相关文章:

angular - 如何在与我的 http 服务器不同的端口上提供 Angular 应用程序

node.js - Node express 公司和路线

javascript - 将 javascript 数组值转换为具有默认值的对象键

Python - 动态导入后未定义的类名

javascript - react 登录,授权成功后移动到新 View

python - 在 Python 中排序名称列表,忽略数字?

python - 将 url 路由到 GAE Flex 服务器,而站点的其余部分在 GAE Standard 上运行

http - 如何在不将请求传递给 Web 服务器的情况下使用 HAProxy 发送响应

javascript - V8 如何优化超大数组的创建?

javascript - 如何从两个不同的函数调用更改状态?