【发布时间】:2021-12-29 19:35:13
【问题描述】:
我试图让用户使用 nestjs 后端登录,当我使用 Postman 时,该过程非常顺利,但使用 Flutter 我不知道该怎么做。我认为我并不真正了解移动设备的会话如何工作,我尝试寻找一些适当的解释,但到目前为止我找不到任何东西。
Nestjs 代码
@Controller('users')
@Serialize(UserDto)
export class UsersController {
constructor(
private usersService: UsersService,
private authService: AuthService,
) {}
@Get('/whoami')
@UseGuards(AuthGuard)
whoAmI(@currentUser() user: User) {
return user;
}
@Get()
getUsers(@Query('email') email: string) {
return this.usersService.find(email);
}
@Post('/signup')
async sendUser(@Body() body: UserDto, @Session() session: any) {
console.log(body);
const user = await this.authService.signup(body.email, body.password);
session.userId = user.id;
console.log(session.userId);
return user;
}
@Post('/signin')
async signin(@Body() body: UserDto, @Session() session: any) {
const user = await this.authService.signin(body.email, body.password);
session.userId = user.id;
console.log(session.userId);
return user;
}
@Post('/signout')
async signout(@Session() session: any) {
console.log(session.userId);
if (!session.userId) {
throw new NotFoundException('user not found');
}
session.userId = null;
}
}
颤振代码
Future<void> signin(
String username, String password, BuildContext context) async {
try {
var url = 'https://example-app.herokuapp.com/users/signin';
var dio = Dio();
var response =
await dio.post(url, data: {'email': username, 'password': password}, options: Options(headers: {'Accept': 'application/json'}));
print(response.headers);
// response;
Navigator.of(context).pushNamed(CategoryDetailScreen.routeName);
} catch (err) {
print(err);
throw err;
}
}
Future<void> signout() async {
try {
var url = 'https://example-app.herokuapp.com/users/signout';
var dio = Dio();
var response = await dio.post(url,
options: Options(headers: {
'cookie':
'key'
}
)
);
print(response.headers);
response;
// return response;
} catch (err) {
print(err);
throw err;
}
}
【问题讨论】:
-
查看带有 cookie 的会话管理:stackoverflow.com/questions/50299253/…
-
@RichardHeap 谢谢,这非常有用,我设法获取了 cookie 并将其保存到设备中。不过,剩下的就是如何让 Flutter 知道用户在更换应用或关闭应用后仍处于登录状态。
-
将 cookie 保存到共享首选项?