I'm trying to send a JSON string to my localhost server using XMLHttpRequest
. Everything works fine with GET
and I can view my response but when I use POST
I get the following error message in console..
XMLHttpRequest cannot load
http://localhost/t
. No 'Access-Control-Allow-Origin' header is present on the requested resource. Originhttp://test.com
is therefore not allowed access. The response had HTTP status code 405.
Request website
var obj = { "table":"customers", "limit":11 };
var dbParam = JSON.stringify(obj);
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
};
var url = 'http://localhost:80/t';
var method = 'POST';
var xhr = createCORSRequest(method, url);
xhr.onload = function() {
console.log("Success");
console.log(xhr.responseText);
};
xhr.onerror = function() {
console.log("Error");
};
xhr.send(dbParam);
On my localhost server I have the following..
Route
Route::post('/t', array('middleware' => 'cors', 'uses' => 'JsonController@getJson'));
Controller
public function getJson(Request $request) {
// First we fetch the Request instance
$request = Request::instance();
// Now we can get the content from it
$content = $request->getContent();
return $content;
}
Cors.php
'supportsCredentials' => true,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['Content-Type', 'application/json'],
'allowedMethods' => ['POST'],
'exposedHeaders' => ['*'],
'maxAge' => 0,