最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - node.js, express, how to get data from body form-data in post request - Stack Overflow

programmeradmin20浏览0评论

I have a simple node.js app. I want to get post body from user.

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);

});

When i launch it with node server.js, its fine. When i check it with postman,

in console, it returns

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

I have the newest express.

And i have try other thing like add body-parser, add header to content-type, add express.urlencoded(), but none work. i need to get data from form-data like postman on picture above. How i can get it?

I have a simple node.js app. I want to get post body from user.

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);

});

When i launch it with node server.js, its fine. When i check it with postman,

in console, it returns

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

I have the newest express.

And i have try other thing like add body-parser, add header to content-type, add express.urlencoded(), but none work. i need to get data from form-data like postman on picture above. How i can get it?

Share Improve this question edited Sep 29, 2020 at 10:00 alfianrehanusa asked Jun 25, 2019 at 16:17 alfianrehanusaalfianrehanusa 2,1142 gold badges21 silver badges34 bronze badges 2
  • Possible duplicate of What does body-parser do with express? – zero298 Commented Jun 25, 2019 at 16:21
  • @zero298 i think is not, because i use the newest express. So i no need body-parser – alfianrehanusa Commented Jun 26, 2019 at 2:15
Add a comment  | 

6 Answers 6

Reset to default 64

after hours, i found it.

body-parser its not required because in newest express is included.

i have found how to get form-data, it require multer(for parsing multipart/form data) middleware. i have found it in here.

first install multer

npm install multer --save

import multer in your app. for example in my code

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;

so, it can receive form-data, raw, or x-www-form-urlencoded.

you need install body-parser to parse req.body

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

body-parser extract the entire body portion of an incoming request stream and exposes it on req.body.

Express specifies in their API docs that you have to use one of the provided middlewares to give the body a value. They made this decision because there are many different kinds of formats HTTP request bodies can take, and they don't want to assume which one your app uses.

Did you add Content-Type: application/json to Headers? I had the same problem and was solved adding Content-Type: application/json.

I had face same problem.I had solved following way:

  1. First install 'express-fileupload' package.

  2. include express-fileupload

    fileUpload = require('express-fileupload')

  3. enable files upload

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

N.B: Or You can use multer package instead of express-fileupload package.as your wish.

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.

    

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论