简体   繁体   中英

Laravel + vueJs + axios, bearer token not working

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

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');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM