Node.js、Express:如何从 POST 请求的表单数据中获取数据

23
我有一个简单的node.js应用程序。我想要获取用户的post body。

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启动时,它很好。当我用postman检查时, enter image description here 在控制台中,它返回
Web App Hosted at http://localhost:3000
{}
undefined

我有最新的express。

我尝试了其他方法,例如添加body-parser,在content-type中添加头部,添加express.urlencoded(),但都没有效果。我需要从form-data中获取数据,就像上面图片中postman一样。我该怎么做?


可能是What does body-parser do with express?的重复问题。 - zero298
@zero298 我认为不需要,因为我使用的是最新的 Express。所以我不需要 body-parser。 - alfianrehanusa
6个回答

58

在工作时间以外,我找到了它。

body-parser 不再需要,因为最新版本的 express 已经包含了它。

我已经找到了如何获取表单数据,需要使用 multer(用于解析 multipart/form data 的中间件)。我在这里找到了它:https://www.npmjs.com/package/multer

首先安装 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数据。


7
我也遇到了相同的问题,花了三个小时试图弄清楚出了什么问题。最后,我也忘记在我的路由中包含multer函数 :) - Alisher Musurmonv

4

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

var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
会提取传入请求流的整个正文部分,并在 req.body 上公开它。

4
问题中有一张截图,可以看到@alfian5229发送的是一个form-data请求,而不是json格式。因此,在那里使用express.json()是无用的。 - poohitan
@Shubh 是的,我有最新的 Express。 - alfianrehanusa

3

Express在他们的API文档中指定,您必须使用提供的中间件之一赋值给body。他们做出了这个决定,因为HTTP请求正文可以采用许多不同格式,并且他们不想假设您的应用程序使用哪一种。

最初的回答:

在Express的API文档中明确指出,您需要使用提供的中间件之一来设置请求正文的值。他们做出了这个决定是因为HTTP请求正文可以采用许多不同格式,他们不能假设您的应用程序使用哪一种。


1
你是否在headers中添加了Content-Type: application/json?我之前遇到同样的问题,通过添加Content-Type: application/json解决了这个问题。

是的,但仍未定义。 - alfianrehanusa
1
它在express v4.17.1中没有解决。 - Veeresh Devireddy

1
我曾经遇到过相同的问题。我是以下方式解决的:
1. 首先安装 'express-fileupload' 包。 2. 引入 express-fileupload 包: fileUpload = require('express-fileupload') 3. 启用文件上传: app.use(fileUpload({ createParentPath: true })); 注意:您也可以根据自己的喜好使用 multer 包代替 express-fileupload 包。

-1
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.

    

3
请问您能否解释一下这是如何回答用户的问题的? - Yves Gurcan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接