没有'Access-Control-Allow-Origin'标头错误,但是在服务器响应中设置了标头

时间:2016-04-15 12:57:50

标签: javascript jquery ajax rest cross-domain

我正在尝试发送跨域请求,但响应是:

jquery-1.12.2.min.js:4 OPTIONS http://127.0.0.1:8080/ygo/v1/owner/new send @ jquery-1.12.2.min.js:4n.extend.ajax @ jquery-1.12.2.min.js:4LoginViewModel.self.actionLogin @ app.js:17(anonymous function) @ knockout.js:98n.event.dispatch @ jquery-1.12.2.min.js:3r.handle @ jquery-1.12.2.min.js:3
index.html:1 XMLHttpRequest cannot load http://127.0.0.1:8080/ygo/v1/owner/new. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:1010' is therefore not allowed access. The response had HTTP status code 405.
app.js:34 {"login":"admin","password":"admin","autologin":"true"}

这是我的脚本(Knockout):

function Login(data) {
    this.login = ko.observable(data.login);
    this.password = ko.observable(data.password);
    this.autologin = ko.observable(data.autologin);
}

function LoginViewModel() {
    var self = this;
    self.login = ko.observable("admin");
    self.password = ko.observable("admin");
    self.autologin = ko.observable("true");

    self.actionLogin = function() {
        $.ajax({
            type: "post",
            url: "http://127.0.0.1:8080/ygo/v1/owner/new",
            data: ko.toJSON({ login: self.login, password: self.password, autologin: self.autologin }),
            dataType: "json",
            crossDomain: true,
            async: true,
            contentType: "application/json",
            success: function(result) {
                console.log(result)
            },
            error: function(result) {
                console.log(ko.toJSON({ login: self.login, password: self.password, autologin: self.autologin }))
            }

        });
    };

}

ko.applyBindings(new LoginViewModel());

我正在使用Python Bottle作为示例本地存根API。这是示例代码:

@route('/ygo/v1/owner/new', method='POST')
def index():
    response.content_type = 'application/json'
    response.headers['Access-Control-Allow-Origin'] = '*'
    login = request.json['login']
    password=request.json['password']
    autologin=request.json['autologin']
    if login=="admin" and password=="admin":
        rs={"Success":True, "info":[]}
    else:
        rs={"Success":False, "info":[{"error":True, "message":"User/Password is incorrect.", "code":10}]}
    return dumps(rs)

您会在存根中看到“允许原点”设置为“*”。据我所知,解决方案是我应该在我的POST请求中的OPTIONS中发送«Access-Control-Allow-Origin»值,但我不知道如何正确地执行它。

0 个答案:

没有答案