1

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://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,
Phil
  • 128,310
  • 20
  • 201
  • 202
mattjon
  • 29
  • 1
  • 8
  • Your JS code is sending a JSON request body so there will be no `$_POST['dbParam']`. I'm sure a quick Google search will reveal how to read raw request body data in Laravel. You should also set a request header of `Content-type: application/json` – Phil Aug 02 '17 at 13:14
  • https://stackoverflow.com/a/33298205/283366 – Phil Aug 02 '17 at 13:17
  • Thanks @Phil! I've made the changes you suggested but now I get a 500 error. ` (index):1 XMLHttpRequest cannot load http://localhost/t. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://test.com' is therefore not allowed access. The response had HTTP status code 500.` – mattjon Aug 02 '17 at 13:30
  • 1
    What on Earth are you doing in your controller? Why `$request = Request::instance()`? You already have the `$request`. It should just be `$content = $request->json()->all();`. Also, if you get an error response (405, 500, etc), the first thing you should do is check your server's error log – Phil Aug 02 '17 at 13:34
  • SOLVED. It was a problem with the CSRF token. – mattjon Aug 02 '17 at 14:03

0 Answers0