Parse the four data formats of post requests based on node. js dependency express, node. jsexpress
Node. js depends on express to parse the four data formats of post requests
There are four types:
- Www-form-urlencoded
- Form-data
- Application/json
- Text/xml
1. www-form-urlencoded
This is the default data format for http post requests and must be supported by the body-parser middleware.
Server demo:
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);
You can use postman for testing. I will not go into details here.
2. form-data
This method is generally used for data upload and requires the support of the middleware connect-multiparty.
Server demo:
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 for parsing.
app.use(bodyParser.json());
4. text/xml
Body-parser does not support this data format by default.
Solution: Read the Request body parameters according to the string, parse the string into a json object using the xml2json package, and perform operations on the json object, which is much easier.
Note: We still need to use body-parse to get the string and then convert it.
Use the event data defined on req to obtain the http request stream. The end event ends the processing of the request stream.
Use xml2json to convert the above request parameter stream (we directly convert it to a string) to a json object.
The 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 the receiving 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 (0, 3000 );
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.