【问题标题】:node.js, express, how to get data from body form-data in post requestnode.js,express,如何在发布请求中从正文表单数据中获取数据
【发布时间】:2021-03-24 09:48:37
【问题描述】:

我有一个简单的 node.js 应用程序。我想从用户那里获取帖子正文。

app.js

var express = require('express');
var app = express();

app.use(express.json());

app.post('/api/user', function (req, res) {
    console.log(req.body);
    console.log(req.body.username);
});

module.exports = app;

server.js

var app = require('./app.js');

var server = app.listen(3000, function () {

    var port = server.address().port;

    console.log('Web App Hosted at http://localhost:%s',port);

});

当我使用node server.js 启动它时,它很好。当我与邮递员检查时,

在控制台中,返回

Web App Hosted at http://localhost:3000
{}
undefined

我有最新的快递。

我尝试了其他方法,例如添加body-parser、将标题添加到content-type、添加express.urlencoded(),但没有任何效果。我需要从form-data 获取数据,就像上图中的邮递员一样。我怎样才能得到它?

【问题讨论】:

标签: javascript node.js express


【解决方案1】:

几个小时后,我找到了。

body-parser 不需要,因为包含在最新的 express 中。

我找到了如何获取表单数据,它需要 multer(用于解析多部分/表单数据)中间件。我在here找到它。

首先安装multer

npm install multer --save

在您的应用中导入 multer。例如在我的代码中

var express = require('express');
var app = express();
var multer = require('multer');
var upload = multer();

// for parsing application/json
app.use(express.json()); 

// for parsing application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true })); 

// for parsing multipart/form-data
app.use(upload.array()); 
app.use(express.static('public'));

app.post('/api/user', function (req, res) {
    console.log(req.body);
    console.log(req.body.username);
});

module.exports = app;

因此,它可以接收表单数据、原始数据或 x-www-form-urlencoded。

【讨论】:

  • 我也遇到了同样的问题,花了 3 个小时试图找出问题所在。最后,我也忘了在我的路线中包含我的 multer 函数 :)
  • 感谢您的回答,非常详细和有帮助。
【解决方案2】:

你需要安装body-parser来解析req.body

var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

body-parser 提取传入请求的整个正文部分 流并在 req.body 上公开它。

【讨论】:

  • 问题中有截图,可以看出@alfian5229发送的是form-data请求,不是json。所以express.json()在那里没用。
  • @Shubh 是的,我有最新的快递。
【解决方案3】:

Express 在他们的API docs 中指定您必须使用提供的中间件之一来为正文赋予一个值。他们做出这个决定是因为 HTTP 请求主体可以采用多种不同的格式,而且他们不想假设您的应用使用哪种格式。

【讨论】:

    【解决方案4】:

    您是否在标题中添加了Content-Type: application/json?我遇到了同样的问题,添加 Content-Type: application/json 解决了。

    【讨论】:

    • 是的,但仍未定义
    • express v4.17.1 没有解决
    【解决方案5】:

    我遇到了同样的问题。我已经解决了以下方法:

    1. 首先安装“express-fileupload”包。

    2. 包括快速文件上传

      fileUpload = require('express-fileupload')

    3. 启用文件上传

      app.use(fileUpload({ createParentPath: true }));

    N.B:或者您可以使用 multer 包而不是 express-fileupload 包。如您所愿。

    【讨论】:

      【解决方案6】:
      const express = require("express");
      var multer = require('multer');
      var upload = multer();
      const app = express();
      var multiparty = require('multiparty');
      var util = require('util');
      var bodyParser = require('body-parser');
      app.use(bodyParser.urlencoded({ extended: true }));
      app.use(bodyParser.json());
      app.use(upload.array()); 
      app.use(express.static('public'));
      // default options
      const addFileDetail =  (req, res,next) => {
      //app.post('/upload', function(req, res) {
          
        var sampleFile = req.body.filepath;
         console.log(req.body.filepath);
      //   var uploads = "./"+req.body.filepath+"/"+req.body.org+"/"+req.body.type+'/';
      //       await createDir(uploads);
      //   let uploadPath = uploads;
      
      //   if (!req.files || Object.keys(req.files).length === 0) {
      //     return res.status(400).send('No files were uploaded.');
      //   }
      
      //   // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
      //   sampleFile = req.files.sampleFile;
      //   uploadPath = __dirname + uploadPath + sampleFile.name;
      
      //   // Use the mv() method to place the file somewhere on your server
      //   sampleFile.mv(uploadPath, function(err) {
      //     if (err)
      //       return res.status(500).send(err);
      var form = new multiparty.Form();
      
      form.parse(req, function(err, fields, files) {
        res.writeHead(200, { 'content-type': 'text/plain' });
        res.write('received upload:\n\n');
        res.end(util.inspect({fields: fields, files: files}));
                   console.log('fields: %@', fields);
                   console.log('files: %@', files);
      });
          // res.send('File uploaded!');
      //   });
      }
      
      const createDir = (dirPath) => {
          fs.mkdir(dirPath, { recursive: true }, (err) => {
              if (err) {
                  throw err;
              }
              console.log("Directory is created.");
          });
      }
      
      module.exports = {
         // getfile: getfile,
          addFileDetail: addFileDetail,
         // viewFiles: viewFiles
      };
       i am getting issue in this.
      
          
      

      【讨论】:

      • 您能否解释一下这如何解决用户的问题?
      猜你喜欢
      • 1970-01-01
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      • 2021-10-22
      • 1970-01-01
      • 2022-01-25
      • 2014-12-08
      • 2021-11-01
      相关资源
      最近更新 更多