【发布时间】:2019-10-22 23:00:15
【问题描述】:
我对 VueJS 有点陌生,我想从 Laravel (passport) API 获取数据,因此我使用 npm i axios 进行 API 请求,这是我的脚本代码来自 App.vue 文件:
import axios from 'axios';
export default {
data () {
return {
}
},
created() {
const postData = {
grant_type: "password",
client_id: 2,
client_secret: 'MvEyvm3MMr0VJ5BlrJyzoKzsjmrVpAXp9FxJHsau',
username: 'my-email@gmail.com',
password: '********',
scope: ''
}
axios.post('http://localhost/api/oauth/token', postData)
.then(response => {
console.log(response.data.access_token);
const header = {
'Accept': 'application/json',
'Authorization': 'Bearer ' + response.data.access_token,
};
axios.get('http://localhost/api/api/user', {headers: header})
.then(response => {
console.log(response)
})
})
}
}
API.PHP (API 的路由文件):
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
这是在 Laravel 中修复 CORS 的中间件代码:
public function handle($request, Closure $next)
{
$domains = ["http://localhost:8080"];
if (isset($request->server()['HTTP_ORIGIN'])) {
$origin = $request->server()['HTTP_ORIGIN'];
if (in_array($origin, $domains)) {
header('Access-Control-Allow-Origin: ' . $origin);
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization');
}
}
return $next($request);
}
查看console.log(response.data.access_token),我正在控制台中登录令牌,但下一个请求给我401未授权错误,我尝试了许多解决方案但没有奏效,有什么建议吗?
【问题讨论】:
-
http://localhost/api/api/user应该是http://localhost/api/user不是吗? -
no
http://localhost/api这是我的项目名称,下一个api用于访问 API 路由。 -
请分享路由配置。
-
现在检查我已经更新了!
-
暂时请从 cors 设置中删除域验证..
标签: javascript laravel vue.js http-headers axios