Jquery: Cross-domain ajax 'POST' with laravel

▼魔方 西西 提交于 2019-12-23 04:45:15

问题


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

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:

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 Allowed in header response

What is the solution for this problem?


回答1:


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

JQuery function:

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:

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.



来源:https://stackoverflow.com/questions/27311091/jquery-cross-domain-ajax-post-with-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!