【问题标题】:laravel's session issue: can't retrieve data from session when router in api.phplaravel 的会话问题:在 api.php 中路由时无法从会话中检索数据
【发布时间】:2017-10-26 08:49:50
【问题描述】:

我正在尝试按会话传递数据。

我的控制器中有两个功能:

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 中的参数(eg.location.replace('edit-estate?estate_id=15');


有我的新问题:
1.如何将令牌放在标题中?
2.如果我要传一个json怎么办?

【问题讨论】:

  • 这是因为 api 文件中定义的路由是无状态的,这意味着您不能在请求中使用会话,但可以使用标头和令牌
  • @AmrAly 感谢您的回复,我在底部修复了我的代码,请看一下。

标签: php laravel session


【解决方案1】:

默认情况下,您不应在 api 中使用会话,因为 larval 不会在 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 服务而不是会话,您最好使用 post 参数和基于令牌的身份验证,但对于 API 和 Web 请求,您可以使用 Web 中间件而不是 api(不推荐)。

【讨论】:

  • 感谢回复,我在底部修复了我的代码,请看一下。
  • @jimmy 你最好在一个单独的问题中提出你的新问题,因为它与主题无关。无论如何,我不熟悉 iOS 编程,但我知道你可以发送令牌和数据(如以及 JSON 编码的数据)使用 POST 协议。
猜你喜欢
  • 1970-01-01
  • 2018-09-28
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
  • 2021-02-11
  • 2021-09-20
  • 2019-12-09
相关资源
最近更新 更多