Language:

Search

Handle CORS Requests with VueJS Client and Laravel API

  • Share this:
Handle CORS Requests with VueJS Client and Laravel API

The Problem

Method POST is not allowed by Access-Control-Allow-Methods in preflight response.

This issue might have occurred before you while developing an application which consists of API calls at each step. Here we're concerned with VueJS Client & LaravelAPI, to be specific. Let's discuss some of possible solutions to tackle this behaviour and fix it for once and forever.

The Solution? Solutions*

Solution # 01

This is the most simplest, dirtiest and yet quickest solution for this problem, simply add the following lines in your web/routes.php file to allow CORS for your application.

header('Access-Control-Allow-Origin:  *');
header('Access-Control-Allow-Methods:  POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers:  Content-Type, X-Auth-Token, Origin, Authorization');

Solution # 02

This second solution may also be considered as dirty as per my taste. But works fine for quick results. Add the below code in the start of your public/index.php file & replace your API & Client URIs to allow CORS for your application.

$allowedOrigins = array(
   '(http(s)://)?(www\.)?your_api_domain\.com', // Laravel API Domain
   'http://my_vue_client.dev' // VueJS CLient
);
if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] != '') {
   foreach ($allowedOrigins as $allowedOrigin) {
      if (preg_match('#' . $allowedOrigin . '#', $_SERVER['HTTP_ORIGIN'])) {
         header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
         header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
         header('Access-Control-Max-Age: 1000');
         header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
         break;
      }
   }
}

Solution # 03

Create a CORS middleware and set everything there, likeso

php artisan make:middleware CorsMiddleware

Now inside of the handle method of CorsMiddleware

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

$headers = [
 'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
 'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
];
if($request->getMethod() == "OPTIONS") {

 return response()->make('OK', 200, $headers);
}

$response = $next($request);
foreach($headers as $key => $value)
 $response->header($key, $value);
return $response;

Register the middleware in app\Http\Kernel.php

protected $routeMiddleware = [
   'cors' => \App\Http\Middleware\CorsMiddleware::class,
];

And use it in your routes,

Route::middleware('cors')->group(function(){
   //your_routes
});

Solution # 04

You can use any of the packages available for handling CORS specifically. Following is one of my favourite package for CORS, you my try this as well.

  • https://github.com/barryvdh/laravel-cors

Conclusion

You can use any of the above method to tackle CORS issue in your Laravel based application. If you have any other way out rather then these approaches, do let us know in the comment section below.

Note that, all of the above solutions are tried and tested and worked great. If you have any queries regarding this article, leave us a comment below. You can also follow us on Twitter.

Usama Muneer

Usama Muneer

A web enthusiastic, self-motivated & detail-oriented professional Full-Stack Web Developer from Karachi, Pakistan with experience in developing applications using JavaScript, WordPress & Laravel specifically. Loves to write on different web technologies with an equally useful skill to make some sense out of it.