【问题标题】:Laravel + vueJs + axios, bearer token not workingLaravel + vueJs + axios,不记名令牌不起作用
【发布时间】:2019-04-07 14:30:05
【问题描述】:

我正在尝试学习如何使用安装的 Axios 和 Laravel cors 为 vue.js 应用构建基本 API。

我可以让 api 执行大多数调用,例如登录、注册、访问不安全区域,但是当我尝试访问受保护区域时,它会在我的浏览器控制台中返回此错误

无法加载http://127.0.0.1:8000/api/closed:对预检的响应 请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:8080” 访问。

这是我的 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

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

    }
}

编辑: 使用邮递员模拟请求工作正常 postman example

【问题讨论】:

  • 您能否确认您的{{ csrf_token }} 在您的<head> 中的mmeta 标记内?
  • 我不认为我的头上有一个 csrf_token,它是一个 vueJs SPA。 Laravel 需要一个吗?
  • 是的,您需要定位文档头部中的那个。如果它不存在,您可以使用元标记。但是这个令牌必须得到正确的令牌。
  • 如果我只使用 Laravrel 作为 API 是不是也一样。网站的前端可能会在不同的服务器上。我希望在某个时候也将它用作移动 api
  • 另外,当我通过邮递员发送请求时,它可以在没有 CSRF 令牌的情况下工作

标签: laravel laravel-5 vue.js axios


【解决方案1】:

我找到了解决这个问题的方法

我需要在路由的中间件中添加 cors

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

【讨论】:

    猜你喜欢
    • 2015-08-01
    • 2017-04-20
    • 1970-01-01
    • 2019-05-28
    • 2018-04-23
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 2020-07-22
    相关资源
    最近更新 更多