Smart Site Developers Knowledgebase

Handle CORS Requests with Client & 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. Let’s discuss some of possible solutions to tackle this behaviour and fix it for once and forever.

The 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.

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.

Solution # 03

Create a CORS middleware and set everything there, like so

php artisan make:middleware CorsMiddleware

Now inside of the handle method of CorsMiddleware

Register the middleware in app\Http\Kernel.php

And use it in 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: laravel-cors.


Leave a Reply