mercredi 2 août 2017

Error using POST with JSON string and CORS

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. Origin http://omerta.se 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) {

        $obj = json_decode($_POST["dbParam"], false);

        return $obj;
    }

Cors.php

'supportsCredentials' => true,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['Content-Type', 'X-Requested-With'],
'allowedMethods' => ['POST'],
'exposedHeaders' => ['*'],
'maxAge' => 0,



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire