Parkicism
Parkicism

Reputation: 2535

No 'Access-Control-Allow-Origin' error with Laravel and React

I am sending a request from my react app localhost:8080 to my lumen api localhost:8000 to retrieve json data.

This is my routes.php in lumen: $app->get('list', 'ArticleController@listAll');

And this is my ArticleController.php in lumen:

<?php

namespace App\Http\Controllers;

use Response;
use Illuminate\Support\Facades\Input;
use App\Article as Article;

class ArticleController extends Controller
{
    public function listAll(){
        $articles = Article::all();

        return response()
            ->json($articles)
            ->setCallback(Input::get('callback'));

    }
}

Because I get that error for cross domain fetch, I am trying to use jsonp, but for some reason it's still not working.

This is my code in React:

componentWillMount(){

    fetch('http://localhost:8000/list?callback=asdf', {
        method: 'GET'
    }).then(function(res) {
        console.log(res);
    }).catch(function(err) {
        console.log(err);
    })
}

Any help would be appreciated. I'm very new to this kind of stuff. Thanks

Upvotes: 0

Views: 2585

Answers (1)

Bogdan Savluk
Bogdan Savluk

Reputation: 6312

Problem is that your API server should return correct CORS headers, to allow using it from other domains.

You have two options to solve this:

  1. Add correct CORS in your API responses, there is ready to use solutions like this one https://github.com/barryvdh/laravel-cors or you can even make your own https://gist.github.com/danharper/06d2386f0b826b669552
  2. Use proxy that will add CORS headers (it is possible to add CORS headers to responses using webserver configuration)
  3. Use JSONP

About JSONP - it is pretty valid option, and it will work...

But in your case it is not working, because fetch - is not the way you can use it.

JSONP is about creating script tag with your request url, and waiting for global callback specified in url to be called when script is loaded(What is JSONP all about?). You need to implement it on your own, or better - use libraries implementing it (for example jQuery)

Upvotes: 1

Related Questions