【问题标题】:Html form not sending data in post requestHtml表单未在发布请求中发送数据
【发布时间】:2019-12-04 19:07:41
【问题描述】:

我正在尝试使用 JWT 实现密码重置。我正在向用户发送一封密码重置电子邮件,其中包含他的 ID 和参数中的 JWT。当用户单击此链接时,它会将他重定向到密码输入页面。该页面由以下函数呈现:

router.get('/resetPassword/:id/:token', function(req, res) {
  if (req.params.token ==null || req.params.id == null) return res.send('Invalid reset 
       password link');
  Organization.findById({_id: req.params.id}, function(err, org) {
       if (err) return res.send(err);
       if (!org) return res.status(HttpStatus.FORBIDDEN).send('No user associated with this 
                reset password link');
  org.decodePasswordResetToken(req.params.token, function(err, decoded) {
  if (err) return res.status(HttpStatus.INTERNAL_SERVER_ERROR).send(err);
  console.log(`${req.params.id} ${req.params.token}`);
  return res.send('<form action="/api/o/resetpassword" method="POST">' +
       '<input type="hidden" id="id" name="id" value="' + req.params.id + '" />' +
       '<input type="hidden" name="token" value="' + req.params.token + '" />' +
       '<input type="password" name="password" value="" placeholder="Enter your new 
                password..." />' +
       '<input type="submit" value="Reset Password" />' +
    '</form>');
    });
  });
});

以上代码包含我要呈现给用户的表单。现在的问题是当用户单击并提交表单时。 Form 中的值应提交给以下函数,但我没有在正文中获得任何值。虽然我可以使用 GET 请求查看数据,但 post 请求正文为空。

router.post('/resetpassword', function(req, res) {
    const {id, token, password} = req.body;
    Organization.findById({_id: id}, function(err, org) {
      if (err) return res.send(err);
      if (!org) return res.status(HttpStatus.FORBIDDEN).send('No user associated with this 
        reset password link');
      org.decodePasswordResetToken(token, function(err, decoded) {
        if (err) return res.status(HttpStatus.INTERNAL_SERVER_ERROR).send(err);
        // set password for this user
        org.password = password;
        org.save(function(err, org) {
          if (err) return res.send(err);
          res.send('Your password has been successfully changed.');
        });
      });
   });
 });

我是 HTML 和 JS 的初学者。对不起,如果这是一个愚蠢的错误。 :D

【问题讨论】:

  • 您是否安装了正文解析器? express 不填充 req.body 本身,检查节点模块 body-parser
  • 我正在使用app.use(bodyParser.json())。还有什么我需要设置的吗?
  • 通过,默认的 http 表单在 body aaa=1&amp;bbb=2 中发送 url 编码的数据,使用必须指定特殊的 multipart,JSON 在 HTTP 标准中没有,它只用于 ajax 请求

标签: javascript html node.js


【解决方案1】:

对于表单数据,你还需要使用:app.use(bodyParser.urlencoded({extended: true })),然后你会得到req.body中的post数据

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 2021-03-01
    • 2014-02-09
    • 2017-02-11
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    相关资源
    最近更新 更多