期望获得客户端'用用户名调用`req.body.username`。但是,调用“ req.body”返回一个奇怪的格式字符串
问题是,当我在服务器中调用req.body
时,它会返回一个奇怪的格式字符串,而不是json对象
我希望我将其作为JSON对象由于我已经从客户端端传递了它:
const handleSubmit = async e => {
e.preventDefault();
const url = "http://localhost:4000/signup";
var credentials = JSON.stringify({
"username": e.target[0].value,
"email": e.target[1].value,
"password": e.target[2].value
})
const config: AxiosRequestConfig = {
method: 'post',
url: url,
data: credentials,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}
console.log('@singup credentials:', credentials) // <----- CONSOLE LOGS THATS PRINTED
try {
const resp = await axios(config)
console.log('data:',resp.data);
} catch (err) {
// Handle Error Here
console.log('at signup post error:')
console.error(err);
}
}
我的服务器代码是:
app.route("/signup")
.post((req, res) => {
console.log("req.body:")
console.log(req.body) // <----- CONSOLE LOGS THATS PRINTED
var user = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password,
});
user.save((err, docs) => {
if (err) {
console.log('signup POST req fail from /signup endpoint')
res.send("error in signpu post")
} else {
req.session.user = docs;
res.redirect("/dashboard");
}
});
});
我从客户端端和服务器端看到的日志如下:
sstatic.net/uopfu.jpg“ rel =“ nofollow noreferrer 编码在我的服务器代码中打开:
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
要更具体地在我的问题上具体说明:
- 为什么我不将
req.body
作为服务器端的JSON对象?我知道我将数据传递为“ www-form-urlenceded”,那么我是否需要从客户端/服务器端进行编码和解码以将传递数据读取为JSON?我想在我的nodejs后端中调用req.body.username
,以获取从前端传递的用户名。 - 从客户端添加/删除
json.stringify
这里没有效果,不是吗?
如果您需要有关该项目的更多信息,请在下面发表评论,我将编辑帖子以包含询问信息。
The problem is that when I call req.body
in my server, it returns a weird formatted string rather than a JSON object
I am expecting to get it as a JSON object as I have passed it as such from the client side:
const handleSubmit = async e => {
e.preventDefault();
const url = "http://localhost:4000/signup";
var credentials = JSON.stringify({
"username": e.target[0].value,
"email": e.target[1].value,
"password": e.target[2].value
})
const config: AxiosRequestConfig = {
method: 'post',
url: url,
data: credentials,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}
console.log('@singup credentials:', credentials) // <----- CONSOLE LOGS THATS PRINTED
try {
const resp = await axios(config)
console.log('data:',resp.data);
} catch (err) {
// Handle Error Here
console.log('at signup post error:')
console.error(err);
}
}
My server code is:
app.route("/signup")
.post((req, res) => {
console.log("req.body:")
console.log(req.body) // <----- CONSOLE LOGS THATS PRINTED
var user = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password,
});
user.save((err, docs) => {
if (err) {
console.log('signup POST req fail from /signup endpoint')
res.send("error in signpu post")
} else {
req.session.user = docs;
res.redirect("/dashboard");
}
});
});
The logs I see from client side and server side are as follows:
I do have the encoding turned on in my server code as such:
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
To be more specific on my problem:
- Why do I not get the
req.body
as a JSON object in my server side? I understand that I'm passing the data as "www-form-urlencoded", so do I need to encode and decode from client/server side to read the passing data as JSON? I wish to callreq.body.username
in my nodejs backend to get the username that was passed from the frontend. - Adding/Removing
JSON.stringify
from the client side has no effect here, shouldn't it?
If you need further information on the project, please comment below and I'll edit the post to include the asking info.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于数据编码为JSON,因此您需要在请求中使用正确的内容类型:
或者,更容易,让Axios照顾它(因为默认为JSON):
Since the data is JSON-encoded, you need to use the correct content type in your request:
Or, even easier, let Axios take care of it (because it defaults to JSON):