Laravel OPTIONS HTTP method catch all – for CORS API pre-routing

I’m developing an CORS(1) API back-end using Laravel, and was having trouble with the OPTIONS HTTP method routing.
I didn’t want to have to create an OPTIONS route for each URL, and was looking for a way to create an OPTIONS catch all; and POST, GET, and DELETE methods that come after can be routed as usual. 

Here’s what I came up with (end of routes.php):

Route::options(‘{name}’, function($name)
{
    Route::options($name, ‘HomeController@goHome’); // only respond with needed headers
})
->where(‘name’, ‘[A-Za-z0-9]+’);

This way {name} matches any URL word, and the HomeController@goHome responds with a mostly blank page (structure but no content basicly), so that the Access-Control-Allow-Origin and Access-Control-Allow-Headers headers get sent out, and allow things to continue GUI-side.
 

(1)CORS = Cross-Origin Resource Sharing

Laravel OPTIONS HTTP method catch all – for CORS API pre-routing

One thought on “Laravel OPTIONS HTTP method catch all – for CORS API pre-routing

Leave a Reply

Your email address will not be published. Required fields are marked *

Confirm you are human * Time limit is exhausted. Please reload the CAPTCHA.