【发布时间】:2021-12-12 05:41:55
【问题描述】:
我正在编写一个前端应用程序,但在将令牌设置为浏览器中的 cookie 时遇到了困难。
后端托管在heroku中,前端运行在本地主机上
我对 React 的要求:
export const axiosConfig: AxiosRequestConfig = {
withCredentials: true,
headers: {
"content-type": "application/json"
},
};
export const login = async (data: UserLoginData): Promise<UserLoginResponse> => {
const res = await axios.post<UserLoginResponse>(API_URL + "/login", data, axiosConfig);
return res.data;
};
快速设置:
app.use(cookieParser());
app.use(cors({ credentials: true, origin: "http://localhost:3000" }));
///
...
///
export const login = async (request: Request, res: Response, next: NextFunction): Promise<void> => {
try {
if (isBodyEmpty(request))
throw new Error();
const { email, password } = request.body;
if (!(email && password)) {
sendFailResponse(res, 400, "All input is required");
return;
}
const user = await User.findOne({ email });
if (user && (await bcrypt.compare(password, user.password))) {
user.token = await createToken(user._id, email);
res.cookie("token", user.token, { maxAge: 900000, httpOnly: true });
res.status(200).send(constructResponse("Success", user));
return next();
}
sendFailResponse(res, 400, "Invalid Credentials");
} catch (error) {
sendFailResponse(res, 400, error.message);
}
};
【问题讨论】:
-
您能否向我们展示您的客户收到的回复?
-
@MarcRo imgur.com/TCChQWC