Skip to content

Instantly share code, notes, and snippets.

@technoknol
Created April 26, 2017 14:10
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save technoknol/1a35ca4b150215f491d5c807940bd4ef to your computer and use it in GitHub Desktop.
Save technoknol/1a35ca4b150215f491d5c807940bd4ef to your computer and use it in GitHub Desktop.
Enable CORS in laravel 5.4
<?php
# File: app\Http\Middleware\CORS.php
# Create file with below code in above location. And at the end of the file there are other instructions also.
# Please check.
namespace App\Http\Middleware;
use Closure;
class CORS {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next) {
// return $next($request);
header("Access-Control-Allow-Origin: *");
// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization'
];
if ($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return \Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach ($headers as $key => $value)
$response->header($key, $value);
return $response;
}
}
# File:: app\Http\Kernel.php
# Add following line in `protected $middleware` Array.
# \App\Http\Middleware\CORS::class
# And following in `protected $routeMiddleware` Array
# 'cors' => \App\Http\Middleware\CORS::class
@joejose99
Copy link

thanks get it working namespace was the issue

@joejose99
Copy link

hey guys does anyone knows how to tackle the issue of CSRF-TOKE I'll been trying to fixed this for days now but can't get through. I don't know what could be wrong, im having this error. 500 (Internal Server Error) . im runing laravel 5.4 here's is the bit of ajax code.

var requestData= JSON.stringify(dataArray);

$.ajaxSetup({
headers:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},

	}); 
	  $.ajax({
		  data:{"data":requestData, "method":'POST',"_token":'{{csrf_token()}}'},
	 type:"POST",
	url: "result",
	dataType:"JSON",
	 success: function(data) {
         $("#tb1").html(data);
		 
     } 
	   
 });  

@besrabasant
Copy link

besrabasant commented Mar 14, 2018

Awesome.

But I had to remove

header("Access-Control-Allow-Origin: *");

and add it to

$headers = [
        "Access-Control-Allow-Origin"   => "*",
        // Other Options
];

instead to make it work with my tests.

@AnApluss
Copy link

Awesome... Thanks mofrubel, this works for me too

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment