Laravel Blade对接Laravel Passport REST API认证问题求助
兄弟,卡3天确实闹心!咱一步步把Blade对接Passport API的事儿搞定,核心就是把认证token带上,然后正确处理请求和响应就行,往下看:
第一步:先把Token存到Blade视图里
首先得让你的Blade页面能拿到有效的Passport token,有两种常见方式:
- 如果是后端已经获取到token(比如从API拿到后传给视图),可以用隐藏input存储:
<!-- 在Blade视图的合适位置添加 --> <input type="hidden" id="api_token" value="{{ $apiToken }}">
- 如果需要用户在页面上登录获取token,可以加个简单的登录表单,提交到API的
oauth/token接口拿token,之后存到localStorage或者隐藏input里(后面会给代码示例)。
第二步:用原生JS发送带认证头的API请求
不管用fetch还是XMLHttpRequest,关键是要在请求头里带上Authorization: Bearer {token},这里用fetch举个例子(语法更简洁):
// 先拿到存储的token const token = document.getElementById('api_token').value; // 或者从localStorage拿:const token = localStorage.getItem('api_token'); // 调用你的文章详情API fetch('http://你的API域名/api/posts/1', { method: 'GET', headers: { 'Authorization': `Bearer ${token}`, // 核心:带上认证头 'Accept': 'application/json', // 明确告诉API要JSON响应 'Content-Type': 'application/json' } }) .then(response => { // 先检查响应状态,避免拿到错误的非JSON内容 if (!response.ok) { throw new Error(`请求失败!状态码:${response.status}`); } return response.json(); }) .then(postData => { // 成功拿到JSON数据了,想怎么渲染就怎么渲染 console.log('文章详情:', postData); // 比如把内容插到页面的指定容器里 const postContainer = document.getElementById('post-container'); postContainer.innerHTML = ` <h2>${postData.title}</h2> <p>${postData.body}</p> <small>发布时间:${postData.created_at}</small> `; }) .catch(error => { // 处理错误,比如token过期、权限不足、API挂了 console.error('调用API出错:', error); alert('获取文章失败,请检查你的认证信息~'); });
如果需要先实现登录拿token的功能,给你个表单提交的示例:
<!-- 登录表单 --> <form id="login-form"> <input type="email" name="email" placeholder="邮箱" required> <input type="password" name="password" placeholder="密码" required> <button type="submit">登录获取Token</button> </form> <script> document.getElementById('login-form').addEventListener('submit', function(e) { e.preventDefault(); // 阻止表单默认提交 const formData = new FormData(this); // 发送请求到API的token接口 fetch('http://你的API域名/oauth/token', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'password', // Passport密码授权模式 client_id: '你的API客户端ID', // 从API项目的passport客户端获取 client_secret: '你的API客户端密钥', username: formData.get('email'), password: formData.get('password'), scope: '' // 不需要权限范围就留空 }) }) .then(response => response.json()) .then(data => { // 拿到token后存起来,方便后续调用API document.getElementById('api_token').value = data.access_token; localStorage.setItem('api_token', data.access_token); alert('登录成功!现在可以调用API了'); }) .catch(error => { console.error('登录失败:', error); alert('账号或密码错误,请重试'); }); }); </script>
第三步:踩过的坑要注意
- 跨域问题:如果你的Blade项目和API项目是不同域名,API那边必须配置CORS允许跨域请求。在API的Laravel项目里安装
fruitcake/laravel-cors包,然后在config/cors.php里设置:paths包含你的API路由前缀(比如api/*)allowed_origins添加你的Blade项目域名allowed_headers要包含Authorization
- API路由的认证中间件:确保API的
api.php里的目标路由用上了auth:api中间件,比如:
// API项目的api.php Route::get('/posts/{id}', [PostController::class, 'show'])->middleware('auth:api');
- 调试技巧:打开浏览器开发者工具(F12),看Network标签,检查请求头有没有带上
Authorization,响应状态码是什么(401是token无效,403是权限不足,500是API内部错误),响应内容里的错误信息能帮你快速定位问题。
内容的提问来源于stack exchange,提问作者Ahmed Shams
相关产品推荐
相关产品推荐

