当使用邮递员时,后端工作正常,但是当使用react时,后端正在发送一个空对象。
我想要的流量;护照登录端点后端重定向到 getUser 端点并返回用户信息以及会话 cookie,然后使用反应查询存储用户信息。这在使用邮递员时有效
当使用我的反应前端时,我收到一个空对象而不是用户数据。
我已经控制台记录了这些步骤,并看到前端正在将登录数据正确发送到登录护照端点,数据被发送到序列化函数但没有保留。重定向到用户端点后,数据(req.user)在控制台记录为未定义。
前端
export async function login({ username, password }) {
console.log("in apiAuth", username, password);
try {
const response = await axios.post(
"http://localhost:3000/users/sessions",
{
username,
password,
},
{
withCredentials: true,
headers: {
"Content-Type": "application/json",
Accept: "*/*",
},
}
);
console.log(response);
return response;
} catch (error) {
console.error(error);
}
}
import { useMutation, useQueryClient } from "@tanstack/react-query";
// import { useNavigate } from "react-router-dom";
import { login as loginAPI } from "../../services/apiAuth";
export function useLogin() {
const queryClint = useQueryClient();
// const navigate = useNavigate();
const { mutate: login, isLoading: isLoggingIn } = useMutation({
mutationFn: ({ username, password }) => loginAPI({ username, password }),
onSuccess: (user) => {
console.log(user);
queryClint.setQueryData(["user"]);
// navigate("/landing", { replace: true });
},
onError: (err) => {
console.error("ERROR in login", err);
},
});
return { login, isLoggingIn };
}
后端
/* Auth */
app.post(
"/users/sessions",
pauth("local", {
successRedirect: "/user",
})
);
用户控制器
async function get(req, res, next) {
try {
console.log("inget", req.isAuthenticated());
res.json(await user.get(req.user));
} catch (err) {
console.error(`something happened while editing user`, err.message);
next(err);
}
}
使用邮递员时,我得到了 req.user 对象,但我的 React Front 返回一个空对象。
从 React 前端向后端发出请求时,请确保将 CORS(跨源资源共享)设置配置为允许随请求发送凭据 (cookie)。这是必要的,因为您的前端和后端在开发过程中由不同的来源提供服务。
// On your Express backend
const corsOptions = {
origin: 'http://localhost:3001', // or your React app's origin
credentials: true, // to allow sending of cookies
};
app.use(cors(corsOptions));