【问题标题】:html multipart/form-data error in req.body using node/express使用 node/express 的 req.body 中的 html multipart/form-data 错误
【发布时间】:2015-05-13 09:53:01
【问题描述】:

我正在使用 node、express、html 并且我正在尝试使用 html 表单将 a 发布到我的服务器端。 问题是我将 {} 作为我的 req.body。

我的html表单如下:

    <form method = 'post' action='get_name' enctype="multipart/form-data">
      <input type="text" name="form_name"><br>
      <input type="submit" value="Upload name">
    </form>

我在 node.js 文件的开头使用以下内容:

app.use(bodyParser.urlencoded({limit:'5mb', extended:false}));
app.use(busboy());

我的 app.post 如下:

app.post('/get_name',function(req, res, next){
        console.log("the name of the form is : ", req.body);
        res.redirect('/admin');
});

当我试图获取 req.body.form_name 时,我得到了未定义。我无法找出我的代码有什么问题。欢迎任何建议。 :)

【问题讨论】:

    标签: html node.js forms express


    【解决方案1】:

    对 multipart/form-data 使用 connect-multiparty 模块,并将其添加到 API 路由的中间件中。

    let multipart = require('connect-multiparty');
    let multipartMiddleware = multipart();
    
     router.route('/customer').post(validate(validations.customerValidation.registerCustomer),multipartMiddleware,CONTROLLER.CustomerBaseController.registerCustomer);
    

    它对我有用。

    【讨论】:

      【解决方案2】:

      如果你要使用 busboy,你应该遵循文档:

      https://github.com/mscdex/busboy

      否则,bodyParser() 不支持多部分表单数据。我个人推荐这个库,因为它很简单:

      https://www.npmjs.com/package/multer

      这将以您打算使用它的方式填充 req.body。

      【讨论】:

      • 因为 bodyParser() 不支持多部分表单数据,如果你想填充 req.body,请尝试使用这个库:npmjs.com/package/multer .. 我个人使用它而不是其他选项,因为它是简单
      【解决方案3】:

      试试这个:

      app.post('/get_name',function(req, res, next){
              console.log("to name of the form is : ", req.param('form_name'));
              res.redirect('/admin');
      });
      

      【讨论】:

      • 你的req.params 可能比其他console.log 更值得console.log(),看看你是否能在其中找到正确的信息。
      猜你喜欢
      • 2023-03-30
      • 2022-10-07
      • 1970-01-01
      • 1970-01-01
      • 2018-06-25
      • 1970-01-01
      • 2015-01-30
      • 2016-11-11
      • 2019-05-15
      相关资源
      最近更新 更多