【问题标题】:Jquery: Cross-domain ajax 'POST' with laravelJquery:使用 laravel 的跨域 ajax 'POST'
【发布时间】:2015-02-03 08:09:32
【问题描述】:

我正在尝试从 jquery 的另一个域的 laravel 服务器上执行 ajax 'POST'。我的 laravel Route 包含以下代码:

Route::post('auth', function(){
$data = Input::get('username');
return Response::json($data->toArray())->setCallback(Input::get('callback'),JSON_PRETTY_PRINT);
});

我的客户端来自不同的服务器,而 JQuery ajax 'POST' 是:

function authUser(appId){
var data = '{"username": "' + appId + '"}';
$.ajax({
    url: "http://localhost:8080/auth",
    type: "POST",
    dataType: 'jsonp',
    data: JSON.stringify(data),
    processData: false,
    contentType: 'application/json',
    CrossDomain:true,
    async: false,
    success: function (data) {
        console.log(data);
    },
    error: function (xhr, ajaxOptions, thrownError) { //Add these parameters to display the required response
        alert(xhr.status);
        alert(xhr.responseText);
    }
});
}

我在标题响应中收到 405 Method Not Allowed

这个问题的解决方法是什么?

【问题讨论】:

    标签: jquery laravel cross-domain cors


    【解决方案1】:

    我自己解决了这个问题,将数据类型更改为 json 并在 apache 中添加标头。

    jQuery函数:

    function authUser(appId){
        var data = '{"username": "' + appId + '"}';
        $.ajax({
            url: "http://localhost:8080/auth",
            type: "POST",
            dataType: 'json',
            data: JSON.stringify(data),
            processData: false,
            contentType: 'application/json',
            CrossDomain:true,
            async: false,
            success: function (data) {
                console.log(data);
            },
            error: function (xhr, ajaxOptions, thrownError) { //Add these parameters to display the required response
                alert(xhr.status);
                alert(xhr.responseText);
            }
        });
    }
    

    Apache 中的标头是:

    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Methods "GET, PUT, POST, DELETE, OPTIONS"
    Header set Access-Control-Allow-Headers "Content-Type, Content-Range, Content-Disposition, Content-Description"
    

    我知道 Access-Control-Allow-Origin 到“*”的标头中的 CORS 会使安全性无效,但如果有人需要解决方案,它会写在那里。

    【讨论】:

    • 这是错误的。如果你想从另一个域做 ajax 发布请求,那么你应该只做一个请求 csrftoken 的 ajax 请求,然后将它与 ajax 发布请求一起传回
    • 需要 json.stringify 吗?如果我没记错的话,laravel 会从所有请求中解析 json,所以你不需要对你的数据进行字符串化。也许这就是方法不允许错误的原因
    猜你喜欢
    • 1970-01-01
    • 2012-06-05
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 2012-05-18
    • 2011-03-31
    • 2013-06-04
    相关资源
    最近更新 更多