Problem with Cors Laravel project 5.5 and Vuejs

Asked

Viewed 474 times

-1

In an Laravel project using the features of an API I have some logos and I have my endpoints in the Laravel.php api file

<?php

Route::post("auth", "Auth\AuthController@authenticate");
Route::get("user", "Auth\AuthController@getAuthenticatedUser");
Route::post("refresh-token", "Auth\AuthController@refreshToken");

Route::group(["prefix" => "v1"], function(){
    Route::apiResource('clients', 'Api\v1\ClienteFisicoController');
    Route::get("category/{id}/products", 'Api\v1\CategoryController@productForCategory');
    Route::apiResource('categorys', 'Api\v1\CategoryController');
    Route::apiResource('products', 'Api\v1\ProductController');
    Route::apiResource('states', 'Api\v1\EstadoController');
});

the CORS package has been configured in the project insert link description here

then the documentation was followed and after that the authentication was implemented using JTW and so far so good.

the problem is when I try to make a simple component to search for a cep, the detail is that this component behaves as expected when it is in a project vuejs without connection with Laravel, a test-only project.

then I have the Component:

<template>
    <div>
       <input type="text" v-model="cep" v-on:keyup="onSubmit">
    </div> 
</template>
<script>
export default {
    data() {
        return {
           cep:'' 
        }
    },
    methods: {
        onSubmit()
        {
            if(this.cep.length === 8) {
                axios.get('https://viacep.com.br/ws/'+this.cep+'/json/')
                .then(response => {
                    console.log(response.data)
                })
                .catch(error =>{
                    console.log(error)
                })
                .finally(()=>console.log("finally"))
            }
        }
    },
}
</script>

this Component launches in the log the following when there is no project attached to it.

{cep: "77015-012", logradouro: "103 Sul Avenida Juscelino Kubitschek", complemento: "", bairro: "Plano Diretor Sul", localidade: "Palmas", …}

and launches the problem of CORS when it is in the Laravel project. inserir a descrição da imagem aqui

Finally in an attempt I created a middleware Mycors added to the kernel.php in middleware, this file I put the following in its context.

<?php

namespace App\Http\Middleware;

use Closure;

class MyCors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
        ->header('Access-Control-Allow-Origin','*')
        ->header('Access-Control-Allow-Methods','GET,PUT,POST,DELETE,OPTIONS')
        ->header('Access-Control-Allow-Headers','Content-Type, authorization');
    }
}

1 answer

3


This service you’re trying to access is external, therefore nay has as configure the CORS his in its application.

What you can do is route in your backend that accesses this service, for example:

Route::get('address/{cep}', 'Api\v1\AddressController@cepSearch');

And just one example to get an idea of how to do it, without any bullshit or anything:

namespace Api\v1;

use GuzzleHttp\Client;

class AddressController
{
    public function cepSearch(Client $client, string $cep) {
        $response = $client->get("https://viacep.com.br/ws/{$cep}/json/");

        return json_decode($response->getBody(), true);
    }
}

And, in your frontend, you must call this new route created.

So you get around the problem with CORS.

  • 1

    Thank you @Ravan your answer is correct.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.