[英]laravel's session issue: can't retrieve data from session when router in api.php
我正在嘗試通過會話傳遞數據。
我的控制器有兩個功能:
public function setEdit(Request $request){
session(['estateId' => $request->estateId]);
return response()->json(['message' => 'success' ]);
}
public function getEdit(){
return response()->json(['base'=> session('estateId')]);
}
當我在web.php調用getEdit()方法時,它將正確檢索estateId。
web.php:
Route::post('/setEdit', 'API\EstateController@setEdit');
Route::get('/getEdit', 'API\EstateController@getEdit');
但是,如果我在api.php上調用getEdit()方法,它將不會獲得estateId。
api.php
Route::post('/setEdit', 'API\EstateController@setEdit');
Route::get('/getEdit', 'API\EstateController@getEdit');
我很確定自己在前端上做得很好。 當我將路由器從web.php移到api.php時,我沒有忘記更改URL。
那么為什么路由器在api.php中時我不能使用會話
好的,現在我知道使用會話在每個頁面之間傳遞數據似乎是一個壞主意。
這是我的前端,我試圖傳遞數據並重定向。
let apiUrl = '../api/estate/setEdit';
let config = {
headers: {'Authorization': 'Bearer ' + localStorage.getItem('token')}
};
let postItem = {'estateId':estateId};
axios.post(apiUrl, postItem ,config).then(response => {
location.replace('edit-estate');
}).catch(function (error) {
console.log(error);
});
我發現我可以將estate_id用作URL中的參數( 例如location.replace('edit-estate?estate_id = 15'); )
我的新問題是:
1.如何將令牌放入標頭?
2.如果我想傳遞一個json怎么辦?
默認情況下,您不應在api中使用會話,因為在使用api的情況下,幼蟲不會啟動會話。 看kernel.php:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\InitiateApp::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
您最好將發布參數和基於令牌的身份驗證用於api服務而不是會話,但是對於API和Web請求(不建議),可以使用Web中間件代替api。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.