![](/img/trans.png)
[英]Laravel Passport API Authentication not working with Bearer Token
[英]Laravel + vueJs + axios, bearer token not working
我正在嘗試學習如何使用安裝的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');
}
}
編輯:使用郵遞員來模擬請求工作正常郵遞員示例
我找到了解決方案
我需要在路線上將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.