我有一个拉拉维尔后端,并反应在前面。对于开发,在localhost:3000
上运行React,在localhost:8080
上运行Laravel,所以我必须允许Cors。
我已经成功地建立了护照,并能够使用JavaScript使用我的API。
但是在每个请求中,我都必须包括访问受保护的API路由的X令牌,这是可行的,但是对于开发,我想禁用API的CSRF-保护。
我已经尝试将/api
路由添加到VerifyCsrfToken
中的except
数组中,并将中间件从Kernel.php
中删除,但这似乎并没有改变我仍然需要发送CSRF令牌的事实。
我使用Laravel5.8并使用JavaScript fetch来发出请求。
VerifyCsrfToken:
protected $except = [
'/api/*'
];```
我在内核中注释掉了VerifyCsrfToken:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
// \App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
示例API路由:
Route::get('test', function() {
return response()->json(['success' => 'Hello!']);
})->middleware('auth:api');
我如何尝试访问API:
const checkStatus = (response) => {
console.log(response);
if (response.ok) {
return response;
} else {
const error = new Error(response.statusText);
error.response = response;
throw error;
}
}
const parseJSON = res => res.text();
const Fetcher = {
get: (ressource) => {
return fetch(CONSTANTS.API_URL + ressource, {
method: 'GET',
mode: 'cors',
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
//'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
},
credentials: 'include'
})
.then(checkStatus)
.then(parseJSON)
},
post: (ressource, data) => {
return fetch(CONSTANTS.API_URL + ressource, {
method: 'POST',
mode: 'cors',
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
//'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
},
credentials: 'include',
body: data
})
.then(checkStatus)
.then(parseJSON)
}
}
发布于 2019-07-02 10:06:39
试着隔离这个问题。
删除路由中的auth:api中间件:
Route::get('api/test', function() {
return response()->json(['success' => 'Hello!']);
});
注意,url是"api/test“,而不仅仅是"test”,因为您定义了这样的$except数组:
protected $except = [
'/api/*'
];
在没有经过CSRF令牌的情况下打电话。
编辑的
有关auth:api中间件的laravel文档:
Laravel包括一个身份验证保护程序,它将在传入请求时自动验证API令牌。您只需要在任何需要有效访问令牌的路由上指定auth:api中间件:
这意味着您必须将API令牌传递给auth:api中间件下的路由,否则将得到401错误。
发布于 2019-10-21 08:47:06
在“路由”文件夹下,处理api.php中的api路由,而不是web.php中的
https://stackoverflow.com/questions/56843676
复制相似问题