简体   繁体   English

Laravel 5.5 MDN Fetch API设置会话变量不起作用

[英]Laravel 5.5 MDN Fetch API set session variable not working

I'm using Laravel 5.5 我正在使用Laravel 5.5

I am trying to set session variable on GET fetch('/ajax-get-save-session') request. 我正在尝试在GET fetch('/ajax-get-save-session')请求上设置会话变量。

Route::get('/ajax-get-save-session', function() { session(['my_key', 'Saved Session']) });

And when I try to access the session variable my_key in different route. 当我尝试以不同的方式访问会话变量my_key时。

Route::get('/access-session', function() { return session('my_key'); });

NULL value is returned. 返回NULL值。

This routes are registered on Laravel web.php and I'm using MDN fetch API 该路由已在Laravel web.php上注册,我正在使用MDN fetch API

Anyone? 任何人?

If i understand your problem. 如果我理解你的问题。 You are looking for this. 您正在寻找这个。 Try this:- 尝试这个:-

Use Session; //if your are using laravel 5.2 then add in top in routes. php or laravel 5.2 > greater versions in web.php 
// now put data in session
Route::get('/ajax-get-save-session', function() {
 Session::put('my_key','Saved Session');
});
//Access the session
Route::get('/access-session', function() { echo Session::get('my_key') });

Hope it helps! 希望能帮助到你!

It's totally my mistake. 这完全是我的错。 I never thought fetch() API is the one causing my problem. 我从没想过fetch()API是导致我遇到问题的一种。 It says the description 它说的描述

By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).

By doing : 通过做 :

fetch(url, { credentials : 'include' }).then(response => response.json())

SOLVED MY PROBLEM! 解决了我的问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM