我分别以get和post请求的形式向后端发送带有axios的用户登录和注册数据,但我不知道为什么对于登录(get)请求,虽然所有内容似乎完全相同,但快递中的req.body仍未定义。
在react应用程序中,我发送了axios请求,如下所示:
const axiosConfig = {
headers: { "Content-Type": "multipart/form-data" }, // commenting this out and using defaults does nothing
};
function submitHandler(e) {
e.preventDefault();
const axiosUser = axios.create({ baseURL: "http://localhost:3100" });
let userData = new FormData();
userData.append("username", usernameRef.current.value);
userData.append("password", passwordRef.current.value);
if (formState === "login") {
for (let pair of userData.entries()) {
console.log(pair[0] + ", " + pair[1]); // username, x // password y as expected
}
console.log("LOGIN");
axiosUser
.get("/u", userData, axiosConfig)
.then((res) => console.log("success:", res))
.catch((err) => console.log("error:", err))
.then(() => {
navigate("/");
});
} else {
for (let pair of userData.entries()) {
console.log(pair[0] + ", " + pair[1]); // username, x // password y as expected
}
console.log("REGISTER");
axiosUser
.post("/u", userData, axiosConfig)
.then((res) => console.log("success:", res))
.catch((err) => console.log("error:", err))
.then(() => {
navigate("/");
});
}
}在特快专递中,我使用multer upload.none()解析upload.none,因为我的其他路线确实有图像上传到cloudinary:
const upload = multer({ storage }) // cloudinary storage
app.post(
"/u",
upload.none(),
asyncErrorWrapper(async function (req, res) {
const result = await User.findOne({ username: req.body.username });
console.log(result);
if (result) {
console.log(req.body.username);
return res.status(400).send("username already exists");
}
const hashedPw = bcrypt.hashSync(req.body.password, 10);
const newUser = new User({
username: req.body.username,
password: hashedPw,
});
await newUser.save();
console.log(newUser);
console.log(` > new user "${req.body.username}" created`);
res.status(200).send("user created");
})
);
app.get(
"/u",
upload.none(),
asyncErrorWrapper(async function (req, res) {
console.log("LOGIN");
console.log(req.body); // ! undefined, {} if parsed with bodyParser
console.log(req.body.username); // error, undefined with bodyParser
console.log(req.body.password); // error, undefined with bodyParser
res.send(req.body);
})
);我尝试删除没有改变任何内容的axiosConfig,并使用另一个解析器(如bodyParser )代替multer req.body作为一个空对象。
发布于 2022-08-14 14:25:32
Get请求通常没有主体。只有Post/Put等请求有一些。虽然一些实现理论上会支持带有主体的Get请求,但不建议这样做,也不建议在HTTP规范中这样做。
如果您查看axios文档,它没有指定向axios.get添加一个主体的可能性,而只添加请求配置。
您还应该为登录函数使用一个Post请求。
https://stackoverflow.com/questions/73352375
复制相似问题