Ajax request for laravel server

1

My minimundo is as follows, I am developing an API for a bakery, where it can be on the same server or different server, I am using the laravel framework in the 5.2.* version. In order to facilitate the work I did some controllers only in painel administrativo for example of products. In my controllers I check if a json request is coming. This way I know if it is a request or if it is a view that I should return, I programmed it as follows:

 public function index(){
    $produtos =  Produto::all();

    if(Request::wantsJson()){
        return $produtos;
    }else{
        return view('Produto.listProduto', compact('produtos'));
    }
}

Having said that and done all the process and the same been tested, I am trying to consume this data from another website, which in this case would be the main site. My idea is to list all products and return them to a JSON.

In html I use JQUERY to make this request in this way:

$.getJSON('http://localhost:8000/produtos', function(data) {
    console.log(data);
});

In my route in painel administrativo I programmed it as follows:

Route::singularResourceParameters();
Route::resource('produtos', 'ProdutoController');

With all this giving an error in console of my browser , I use google chrome but I tried in others and gave the same type of problem.

The output was

  

Blocked cross-origin request: The Same Origin Policy prevents the remote resource from being read at link . (Reason: CORS 'Access-Control-Allow-Origin' header is not present.)

What can I do wrong?

    
asked by anonymous 04.10.2016 / 01:54

1 answer

1

It must be installed via composer.phar a package to release CORS 'Access-Control-Allow-Origin' , the barryvdh / laravel-cors (Cross-Origin Resource Sharing)

In the command line type :

  

php composer require "barryvdh/laravel-cors"

in file config/app.php in providers add:

Barryvdh\Cors\ServiceProvider::class,

Once installed, type this command line further:

  

php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

You will copy the configuration file to the folder config with the name of cors.php .

Finally on routes ( route ) put a middleware same example below:

Route::group(['middleware' => 'cors'], function(Router $router){
    $router->get('api', 'ApiController@index');
});

If you want to make an improved configuration do in the file config/cors.php , its default is:

<?php
return [
    /*
     |--------------------------------------------------------------------------
     | Laravel CORS
     |--------------------------------------------------------------------------
     |
     | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
     | to accept any value.
     |
     */
    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['*'],
    'exposedHeaders' => [],
    'maxAge' => 0,
    'hosts' => [],
];

Links:

04.10.2016 / 01:57