期望获得客户端'用用户名调用`req.body.username`。但是,调用“ req.body”返回一个奇怪的格式字符串

发布于 2025-02-07 12:29:58 字数 2545 浏览 1 评论 0原文

问题是,当我在服务器中调用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

enter image description here

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:

enter image description here

enter image description here

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 call req.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦里梦着梦中梦 2025-02-14 12:29:58

由于数据编码为JSON,因此您需要在请求中使用正确的内容类型:

headers: {
  'Content-Type': 'application/json',
}

或者,更容易,让Axios照顾它(因为默认为JSON):

const config: AxiosRequestConfig = {
  method: 'post',
  url:    url,
  data:   {
    username: e.target[0].value,
    email:    e.target[1].value,
    password: e.target[2].value
  }
}

Since the data is JSON-encoded, you need to use the correct content type in your request:

headers: {
  'Content-Type': 'application/json',
}

Or, even easier, let Axios take care of it (because it defaults to JSON):

const config: AxiosRequestConfig = {
  method: 'post',
  url:    url,
  data:   {
    username: e.target[0].value,
    email:    e.target[1].value,
    password: e.target[2].value
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文