我使用nestjs开发了一个后端。该系统当前的目的是一个身份验证系统。
const user = await this.prisma.user.findUnique({
where: { email: loginDto.email },
});
if (!user) throw new ForbiddenException('Credentials incorrect');
const pwMatches = await bcrypt.compare(loginDto.password, user.password);
if (!pwMatches) throw new ForbiddenException('Credentials incorrect');
const token = await this.signToken(
user.id,
user.email,
user.nativeLanguage,
);
if (!token) {
throw new ForbiddenException('Something went wrong!');
}
res.cookie('token', token, {
expires: new Date(Date.now() + 90 * 24 * 60 * 1000),
});
return res.send({ message: 'Logged in successfuly!' });
export const auth = async () => {
const res = await fetch('http://localhost:3333/users', {
method: 'GET',
credentials: 'include',
cache: 'no-store',
});
const data = await res.json();
console.log(data);
return data;
};
登录后,我提出此请求,但收到未经授权的错误。
当我通过 POSTMAN 尝试时工作正常,但此方法不起作用
auth 函数应该使用我发送的 cookie 发送成功的请求,并查看 jwt 令牌的解码版本
我怀疑问题在于,在您返回服务器的请求中,您没有在标头中包含正确的授权。在下面的示例中,我显示了带有不记名令牌身份验证标准的身份验证,我不确定您在示例代码中在nestjs中使用什么类型的身份验证,但想法基本相同,您需要在nodejs请求中包含标头.
如果您转到 POSTMAN,您应该会在请求的
Authorization
部分看到应该选择某种形式的身份验证。
在您的请求中,通常会包含如下令牌:
const fetchRes = await fetch(
"https://localhost:3000/users",
{
headers: {
authorization:
"Bearer eyJhbGciOiJSU....",
// Other Headers should be added as well
},
method: "GET",
}
);
const fetchResJson = await fetchRes.json();