我有一个登录过程,在用户成功登录后,会通过"Set-Cookie"
在响应中设置一个cookie。我用一个身份验证中间件设置了我的后端,每当收到新的http请求时,它总是检查cookie。到目前为止,当用户从客户端登录时,cookie被成功存储。但是,当我在客户端上进行另一个请求时,我不知何故丢失了cookie;并且服务器将该新请求视为未授权请求。
登录后的响应标头:
登录后发送请求后的请求头:
验证码:登录-设置Cookie(服务器)
public logIn = async (req: Request, res: Response, next: NextFunction) => {
const logInData: LogInDto = req.body;
const user: UserInterface = await this.User.findOne({ email: logInData.email });
if (user) {
console.log(user);
const passwordMatch: boolean = await this.authService.matchPassword(logInData, user);
console.log(passwordMatch);
if (passwordMatch) {
const token: Token = this.authService.createToken(user);
const cookie: any = this.authService.createCookie(token);
res.setHeader("Set-Cookie", [cookie]);
res.status(200).json(
{
message: "Login success",
user: user
}
);
} else {
next(new CredentialsException());
}
} else {
next(new CredentialsException());
}
}
登录后新建请求(客户端)
const Dashboard: React.FC = () => {
const handleClick = async () => {
const res: any = await axios.get<any>(
"http://localhost:4000/getusers",
{
withCredentials: true
}
);
console.log(res);
}
认证中间件(服务器)
export async function authMiddleware(req: Request, res: Response, next: NextFunction) {
console.log(req.cookies);
const cookies: any = req.cookies;
if (cookies && cookies.Authorization) {
const pubKey: string | Buffer = fs.readFileSync("./server.public.key", "utf8");
try {
let verifyOptions: any = {
algorithm: ["RS256"]
};
const tokenPayload: TokenPayload = jwt.verify(cookies.Authorization, pubKey, verifyOptions) as unknown as TokenPayload;
const _id: string = tokenPayload._id;
const user: UserInterface | null = await User.findById(_id);
if (user) {
req.user = user;
next();
} else {
next(new AuthTokenException())
}
} catch (error) {
next(new AuthTokenException());
}
} else {
next(new AuthTokenException());
}
}
从客户端登录(第一次请求)
export const login = createAsyncThunk(
"auth/login",
async (loginData: LoginData, thunkAPI: any) => {
try {
const { email, password } = loginData;
//config, data, headers, request, status, statusText
//{ data: resData, headers: resHeaders }
const { data: resData, headers: resHeaders } = await axios.post<LoginResponse>(
"http://localhost:4000/login",
{
email: email,
password: password,
},
);
console.log(resData);
console.log(resHeaders);
return resData;
}
catch (error: any) {
console.log(error.message);
console.log(thunkAPI.rejectWithValue(error.message));
return thunkAPI.rejectWithValue(error.message);
}
}
)
当我在handleClick
中发送新请求时,是否需要设置一些头?
1条答案
按热度按时间5ssjco0h1#
由于您正在发送凭据,因此需要指定URL并启用凭据,您不能使用“*”
你不必在第一次请求时启用凭证,因为你只是尝试登录,而且你不是第一次发送任何cookie。你可以查看他们的文档了解更多细节https://github.com/expressjs/cors