如何使用Axios使用经过身份验证的API

问题描述 投票:0回答:1

我正在尝试使用Vue和Laravel构建应用程序。我目前在Laravel中使用护照认证进行用户认证。但是,当我尝试使用axio从vue组件发出发布请求时,即使我当前已登录,也会遭到401未经授权。

这里是一些示例代码:

1。从vue组件获取请求

    getEvents() {
      axios
        .get("/api/calendar")
        .then(resp => (this.events = resp.data.data))
        .catch(err => console.log(err.response.data));
    }

2。 Laravel路线

Route::apiResource('/calendar', 'CalendarController')->middleware('auth:api');

3。与上面的get请求关联的日历控制器

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return CalendarResource::collection(Calendar::all());
    }

我已经花了几个小时来解决这个问题,发现的所有内容根本无法正常工作。因此,非常感谢您的帮助。

edit:更多详细信息我正在使用Laravel 5.8.35。

关于护照,我正在使用本文档laravel.com/docs/5.8/passport,并遵循了installationm前端快速入门和部署步骤。

php laravel vue.js axios laravel-passport
1个回答
1
投票

请确认您是否已在条目metacsrf token文件中为html设置了blade

<meta name="csrf-token" content="{{ csrf_token() }}">

同样也是axios文件中bootstrap.js的标题

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
© www.soinside.com 2019 - 2024. All rights reserved.