curl -H "Content-Type: application/json" -d '{"name":"sparc_core","port":["p1", "p2"]}' http://127.0.0.1:3000/add_module
来测试nodejs服务器。起初,我的代码如下:
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);
... ...
在运行curl命令后,节点服务器输出以下错误信息:
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
然后,我将代码修改为如下形式:
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);
... ...
我运行了相同的curl命令,它正常工作!
因此,我想知道app.use和app.post之间的区别。需要您的帮助,非常感谢。