frame

PHP Lumen How to Resolve CORS Problems once and for all when interfacing with javascript frontend.

CORS (Cross origin resource sharing) rules were made with good intentions in mind. The general idea is that an api, should not serve requests made by another server. Rather, it should only send requests to a client app like postman, curl, or a browser. For instance, if you own www.gmail.com. A guy should not be able to send requests from www.larisoft.com to your server and get valid response. However, they can visit your site using a client app like chrome.

In today's world where distributed applications are the norm and a typical system exists across different servers, CORS rules can be very annoying since these servers typically need to speak with each other while serving requests, and by default, apache servers are set to deny cross origin requests.

For readers who do not know lumen, lumen is a slim version of laravel, which is used mainly for serving json responses and building restful APIs.

Now how to solve CORS problems in lumen?

You need to create CORS accepting headers, and send them with all your responses. You should return all responses with the headers. For instance, instead of

return response->json([“token”=>$token], 400),
do
return response->json([“token”=>$token], 400, $headers);

typical CORS accepting headers would be
private $headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => 'API_KEY, token, Content-Type, Authorization, X-Requested-With'
];

A complete example in a full lumen controller:

<?php

namespace App\Http\Controllers;

use App\Encounter;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class MController extends Controller
{

private $headers  =  [
    'Access-Control-Allow-Origin'      => '*',
    'Access-Control-Allow-Methods'     => 'POST, GET, OPTIONS, PUT, DELETE',
    'Access-Control-Allow-Credentials' => 'true',
    'Access-Control-Max-Age'           => '86400',
    'Access-Control-Allow-Headers'     => 'API_KEY, token, Content-Type, Authorization, X-Requested-With'
];




public function delete(Request $request, $id)
{

    return response()->json($data, 200, $this->headers); 
}

public function list(Request $request)
{   
    return response()->json($data, 200, $this->headers);
}

public function detail(Request $request, $id)
{ 

    return response()->json($data 200, $this->headers);
}

public function edit(Request $request, $id)
{

....
return response()->json(["message"=>"Missing fields"], 200, $this->headers);

}

}

Comments

  • This thing too dey give headache, you fire jquery ajax, tor e fail. Thanks for this topic.

  • Thanks, Boss

Sign In or Register to comment.

Africoders

© Africoders 2014 - 2019, All rights reserved. You will also find Africoders on FreeBasics.

Get In Touch