我目前正在开发一个预订系统,我使用的身份验证是JWT并将其保存在我的cookie中。这就是我在用户登录后发送cookie的方式。
const login = async () => {
const requestOptions = {
credentials: 'same-origin',
withCredentials: true,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
path: '/',
body: JSON.stringify({
id: "User ID",
password: "Password"
})
};
fetch('https://localhost:4000/auth/login', requestOptions)
.then(res => res.json())
.then(response => {
console.log('result login', response)
})
.catch((e) => {
console.log('[error] login', e)
})
// empty dependency array means this effect will only run once (like componentDidMount in classes)
};
useEffect(() => {
login()
}, []);
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
@UseGuards(LocalGuard)
@Post('login')
async login(
@Body() data: UserLoginDto,
@Res({ passthrough: true }) res: Response,
) {
console.log('[LOGIN]', data);
const access_token = this.authService.login(data);
res.cookie('access_token', access_token, {
httpOnly: true,
secure: true,
sameSite: 'none',
path: '/',
maxAge: 10000,
expires: new Date(Date.now() + 1 * 24 * 60 * 1000),
});
return access_token;
}
然后我就可以看到这样的cookie数据了。
我尝试过凭据、https、httpOnly、安全、sameSite、过期选项。但这些都不起作用,仍然进去了。 有没有办法存储cookie?请帮助我。
我猜这是您的测试环境,因此 React 应用程序与 Nest.js 应用程序运行在不同的端口上,对吗?
您的 Nest 应用程序需要允许 React 应用程序的 CORS 来源。将其添加到您的 main.ts 中:
app.enableCors({
origin: [
'http://localhost:3000',
],
});
将端口号替换为您的 React 应用程序的端口。
如果您有兴趣,请进一步阅读 CORS:https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS