node.js,表达,如何在请求后从表单数据中获取数据

时间:2019-06-25 16:17:13

标签: javascript node.js express

我有一个简单的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启动它时,就可以了。当我和邮递员核对时, enter image description here

在控制台中,它返回

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

我有最新的快递。

我尝试了其他操作,例如添加body-parser,将header添加到content-type,添加express.urlencoded()等,但是没有任何效果。我需要从 form-data 中获取数据,例如图片上的邮递员。我如何得到它?

6 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:1)

Express在其API docs中指定您必须使用提供的中间件之一为主体提供值。他们之所以做出此决定,是因为HTTP请求主体可以采用多种不同的格式,并且他们不希望您的应用使用哪种格式。

答案 2 :(得分:1)

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

答案 3 :(得分:1)

<块引用>

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

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

  2. 包含 express-fileupload

    fileUpload = require('express-fileupload')

  3. 启用文件上传

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

注意:或者您可以根据需要使用 multer 包而不是 express-fileupload 包。

答案 4 :(得分:0)

几个小时后,我找到了。

body-parser并不是必需的,因为在新快递中包括了。

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

首次安装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。

答案 5 :(得分:0)

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.

    
相关问题