Jquery:使用 Laravel 跨域 ajax 'POST'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27311091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:31:28  来源:igfitidea点击:

Jquery: Cross-domain ajax 'POST' with laravel

jquerylaravelcross-domaincors

提问by PaladiN

I'm trying to do an ajax 'POST' on laravel server from another domain from jquery.My laravel Route consists of the codes below:

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

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

My client is from different server, and the JQuery ajax 'POST' is:

我的客户端来自不同的服务器,而 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);
    }
});
}

I am getting 405 Method Not Allowedin header response

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

What is the solution for this problem?

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

enter image description here

在此处输入图片说明

回答by PaladiN

I solved it myself by changing the data type to jsonand adding headers in apache.

我自己通过将数据类型更改为json并在 apache 中添加标头来解决它。

JQuery function:

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

The headers in Apache are:

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"

I know the CORS in Headers for Access-Control-Allow-Origin to "*" voids the security but if someone needs the solution it's write up there.

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