Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

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

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, enter image description here

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...