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

喜夏-厌秋 提交于 2020-04-10 05:29:30

问题


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(), etc but none work. i need to get data from form-data like postman on picture above. How i can get it?


回答1:


after hours, i found it.

body-parser its not required because in new 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 tutorialspoint.com.

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.




回答2:


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.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/56758241/node-js-express-how-to-get-data-from-body-form-data-in-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!