I use command curl -H "Content-Type: application/json" -d '{"name":"sparc_core","port":["p1", "p2"]}' http://127.0.0.1:3000/add_module
to test nodejs server.
At first, my code is as follows:
app.post('/add_module', bodyParser.json());
app.post('/add_module', bodyParser.urlencoded());
app.post('/add_module', function(req, res, next) {
req.body = JSON.parse(req.body.data);
next();
});
app.post('/add_module', function(req, res) {
console.log("Start submitting");
console.log(req.body);
... ...
After I run curl command, the nodes server output error information as below:
SyntaxError: Unexpected token u
at Object.parse (native)
at Object.app.post.res.send.error [as handle] (/home/xtec/Documents/xtec- simict/sim/app.js:80:21)
at next_layer (/home/xtec/Documents/xtec- simict/sim/node_modules/express/lib/router/route.js:103:13)
at Route.dispatch (/home/xtec/Documents/xtec-simict/sim/node_modules/express/lib/router/route.js:107:5)
at /home/xtec/Documents/xtec- simict/sim/node_modules/express/lib/router/index.js:205:24
at Function.proto.process_params (/home/xtec/Documents/xtec-simict/sim/node_modules/express/lib/router/index.js:269:12)
at next (/home/xtec/Documents/xtec-simict/sim/node_modules/express/lib/router/index.js:199:19)
at next_layer (/home/xtec/Documents/xtec-simict/sim/node_modules/express/lib/router/route.js:77:14)
at Object.urlencodedParser [as handle] (/home/xtec/Documents/xtec-simict/sim/node_modules/body-parser/index.js:67:27)
at next_layer (/home/xtec/Documents/xtec-simict/sim/node_modules/express/lib/router/route.js:103:13)
POST /add_module 500 7ms - 1021b
then, I modify the code as follows:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/add_module', function(req, res) {
console.log("Start submitting");
console.log(req.body);
... ...
I run the same curl command , It works OK!
So I want to know the differents between app.use and app.post. Need your help, thank you very much.