2014-12-05 118 views
0

我试图从jquery.My laravel路线另一个域做laravel服务器上的AJAX“POST”由代码如下:jQuery的:跨域Ajax“POST”与laravel

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法标头响应不允许

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

enter image description here

回答

2

我通过改变数据类型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" 

我知道在头中CORS的访问控制允许来源为“*”空洞的安全,但如果有人需要它写在那里的解决方案。

+0

这是错误的。如果你想从另一个域做ajax post请求,那么你应该做一个ajax请求,询问一个csrftoken,然后用ajax post请求将它传回。 – Gokigooooks 2015-11-17 07:35:03

+0

是否需要json.stringify?如果我没记错,laravel会解析所有请求中的json,所以你不需要将你的数据串联起来。也许即使这是方法的原因不允许错误 – Gokigooooks 2015-11-17 07:43:06