简体   繁体   English

Laravel + VueJs + Axios,承载令牌不起作用

[英]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. 我正在尝试学习如何使用安装的Axios和Laravel cors为vue.js应用程序构建基本API。

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 我可以让api进行大多数调用,例如登录,注册,访问不安全的区域,但是当我尝试访问受保护的区域时,它将在浏览器控制台中返回此错误

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. 无法加载http://127.0.0.1:8000/api/closed :对预检请求的响应未通过访问控制检查:所请求的资源上没有'Access-Control-Allow-Origin'标头。 Origin ' http://localhost:8080 ' is therefore not allowed access. 因此,不允许访问源' http:// localhost:8080 '。

Here is my Vue JS funciton 这是我的Vue JS功能

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 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 我需要在路线上将cors添加到中间件

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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