Based on node. js Dependent on express Resolving post Request Four Data Formats
- 2021-07-21 06:10:58
- OfStack
node. js Depends on express to parse post request 4 data formats
They are these four kinds:
www-form-urlencoded form-data application/json text/xml
1. www-form-urlencoded
This is the default data format for post requests for http and requires the support of body-parser middleware
demo on the server side:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended:true
}));
app.post('/urlencoded', function(req, res){
console.log(req.body);
res.send(" post successfully!");
});
app.listen(3000);
It can be tested with postman, so I won't go into details here.
2. form-data
This method is generally used for data uploading and needs the support of middleware connect-multiparty
demo on the server side:
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
app.post('/formdata',multipartMiddleware, function (req, res) {
console.log(req.body);
res.send("post successfully!");
});
3. application/json
body-parser middleware supports json parsing. You can add middleware to parse
app.use(bodyParser.json());
4. text/xml
body-parser does not support this data format by default
Solution: It is much more convenient to read the request body parameters according to the string, then parse the string into json object by using xml2json package, and then operate json object.
Note: We still need to use body-parse to get the string and then convert it.
The http request flow is obtained by using the data defined on req, and the end event ends the processing of the request flow.
Use xml2json to convert the request parameter stream obtained above (which we convert directly into a string) into an json object.
demo is as follows:
var express = require('express');
var bodyParser = require('body-parser');
var xml2json=require('xml2json');
var app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/xml', function (req, res) {
req.rawBody = '';// Add receive variable
var json={};
req.setEncoding('utf8');
req.on('data', function(chunk) {
req.rawBody += chunk;
});
req.on('end', function() {
json=xml2json.toJson(req.rawBody);
res.send(JSON.stringify(json));
});
});
app.listen(3000);