问题
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