【发布时间】:2026-01-05 15:15:03
【问题描述】:
使用:
返回: Laravel/Passport 前面: ReactJs/Axios
我想在我的页面中获取数据,如果我运行:
axios.get('http://localhost:8000/api/posts')
.then(response => {
console.log(response.data);
})
.catch((error) => {
console.log('error ' + error);
});
GET http://localhost:8000/api/posts net::ERR_ABORTED 401(未授权)
访问 XMLHttpRequest 在 'http://localhost:8000/api/posts' 来自原点'http://localhost:3000' 已被 CORS 策略阻止:没有“访问控制允许来源” 请求的资源上存在标头。
如果我添加:
headers: {
Authorization: 'Bearer ' + token,
crossDomain: true,
'Access-Control-Allow-Origin': '*'
}
从 'http://localhost:8000/api/posts' 访问 XMLHttpRequest 来源 'http://localhost:3000' 已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。
在 laravel/api.php 中:
Route::middleware('auth:api')->group(function () {
Route::get('posts', 'PostController@index');
});
AuthServiceProvider.php
$this->registerPolicies();
Route::group([ 'middleware' => [ \App\Http\Middleware\CORS::class ]], function() {
Passport::routes();
});
RouteServiceProvider.php
$this->mapApiRoutes();
$this->mapWebRoutes();
Route::group([
'middleware' => ['auth:api', 'cors'],
'namespace' => $this->namespace,
'prefix' => 'auth:api',
], function ($router) {
Route::apiResource('posts','PostController');
});
但是,如果我从 axios 中删除 headers 并将 route 移到护照身份验证之外,它工作正常,我的意思是在组之外这样:
Route::get('posts', array('middleware' => 'cors', 'uses' => 'PostController@index'));
那么,如何在 reactjs 中使用带有 axios 的护照身份验证从 Laravel API 获取数据?
更新:
Route::group(['prefix' => 'auth:api', 'middleware' => 'cors'], function(){
Route::get('posts', 'PostController@index');
});
404(未找到)
我也在群里用cors,但还是一样,404错误。
【问题讨论】:
-
您缺少组中的
cors中间件。 -
@DavinTryon 我在
RouteServiceProvider.php和AuthServiceProvider.php上添加了 cors 组,没什么不同 -
在您的中间件中尝试将
cors作为第一个.. -
@Panther 查看我的答案更新
-
使用类似
Route::group([ 'middleware' => ['cors', 'auth:api'],...
标签: php reactjs laravel cors axios