Consuming Laravel API in React.

Simran Kaur Kahlon
Gray Matrix
Published in
4 min readJan 2, 2020
Image Source — Medium.com

Creating an API in Laravel was quite simple for me, but using it in React or any other Front end language proved to be a little time consuming owing to my lack of knowledge related to CORS.

So CORS?

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin.

A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.

For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts.

In simpler terms, our React app is running on a different domain, port and is trying to access our Laravel API’s which are again on some different domain and port.

So, what do we do for this?

To give you a sum up of what’s coming up next, we firstly create our API’s in Laravel, add a cors middleware to support CORS headers in our Laravel app, and then consume these API’s in React using Fetch.

  1. Start by adding your route to the routes/api.php. In my case, I am implementing the Register User API as:

Route::post(‘register’, ‘Auth\RegisterController@influencer_register’);

Note: You can implement authentication in your API’s using api_token or Laravel Passport.

All the API’s created in Laravel begin with “api” prefix i.e our register endpoint will be as

http://localhost:8000/api/register

2. influencer_register method in Auth\RegisterController is as -

We create the user, generate a token and return a JSON response with user details.

The generateToken() in the User.php model is as -

It’s just generating a random string and saving it in the api_token column in the user table for that user. Don’t forget to add this column in the users migration.

$table->string(‘api_token’,80)->unique()->nullable()->default(null);

This will act as an authentication, as we wish to entertain only valid user requests.

3. So our API is ready and we can test it as -

curl -X POST http://localhost:8000/api/register \
-H “Accept: application/json” \
-H “Content-Type: application/json” \
-d ‘{“name”: “Simran”, “email”: “
xyz@yopmail.com”, “password”: “simran12”, “password_confirmation”: “simran12”}’

Output is as

{
“data”: {
“api_token”:”0syHnl0Y9jOIfszq11EC2CBQwCfObmvscrZYo5o2ilZPnohvndH797nDNyAT”,
“created_at”: “2020–01–01 21:17:15”,
“email”: “
xyz@yopmail.com”,
“id”: 1,
“name”: “Simran”,
“updated_at”: “2020–01–01 21:17:15”
}
}

This api_token has to be passed while calling the APIs that require authentication, registration in my case doesn't require any so I won't be passing it.

4. Now, we will be implementing cors middleware using fruitcake/laravel-cors package.

Install it as: composer require fruitcake/laravel-cors

Add the HandleCors middleware in the $middleware property of app/Http/Kernel.php class:

protected $middleware = [
// …
\Fruitcake\Cors\HandleCors::class,

];

Add the same under api in the $middlewareGroups as well.

Now, you can publish it as: php artisan vendor:publish — tag=”cors”

This will publish the config to copy the file to your own config:

You can make changes to the config/cors.php file according to your needs. Its default content is as follows :

5. With this, we are good to go from the Laravel end. Let’s quickly use it in React as -

Set your headers and pass the form data and wait for the response. The API returns a JSON response as seen above while using the curl command.

So, that's it, now you can consume all your Laravel API from anywhere, provided either there is no authentication needed.

If you are guarding your API’s then you will need to pass appropriate authentication tokens to access them.

Please get in touch in case of any queries.

Thanks.

--

--

Simran Kaur Kahlon
Gray Matrix

JS/ Laravel / AWS / Chatbot Developer #AWS Solution Architect Associate #AWS Developer Associate