0
votes

I'm trying to learn how to build a basic API for a vue.js app using Axios and Laravel cors installed.

I can get the api to to do most calls like, logging in, registering, access unsecured areas but when I try to access a protected area it's coming back with this error in my browser console

Failed to load http://127.0.0.1:8000/api/closed: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

Here is my Vue JS funciton

userArea () {

  const HTTP = axios.create({
    baseURL: `http://127.0.0.1:8000/api/`,
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Credentials": true,
      Authorization: 'Bearer ' + this.token
    }
  })

    HTTP.get('closed')
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });
}

laravel cors.php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * 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, POST, PATCH, PUT, DELETE, OPTIONS')
        ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With');

    }
}

Edit: Using postman to emulate the request works fine postman example

1
Can you confirm your {{ csrf_token }} is within a mmeta tag in your <head>?thisiskelvin
I don't think I have a csrf_token in the head, it's a vueJs SPA. Does Laravel require one?flo
Yes, you will need to target the one within the head of the document. If it's not there you can the meta tag. However this token must get the correct token.thisiskelvin
Is it the same if I'm using Laravrel as just an API. the front end of the site will be on a different server possibly. I as hoping to use it as a mobile api too at some pointflo
Also when i send the request via postman it works without a CSRF tokenflo

1 Answers

0
votes

I found the solution to this one

I needed to add cors to the middleware on the route

Route::group(['middleware' => ['jwt.verify','cors']], function() {
    Route::get('user', 'UserController@getAuthenticatedUser');
    Route::get('closed', 'DataController@closed');
});