node express 中的 app.post 和 app.use 有什么不同?

Tyr*_*ion 2 javascript curl node.js express

我使用命令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);
... ...
Run Code Online (Sandbox Code Playgroud)

运行 curl 命令后,节点服务器输出错误信息如下:

SyntaxError: 在 Object.app.post.res.send.error [作为句柄] (
/home/xtec/Documents/xtec-simict/sim/app.js:80:21) 的 Object.parse (native) 的意外标记 u 在 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) 在下一个 (/home/xtec/Documents/xtec-simict/sim/node_modules/express /lib/router/index.js:199:19)






在 Object.urlencodedParser
[作为句柄] (/home/xtec/Documents/xtec- simict/sim/node_modules/body-parser/index.js:67:27)
在 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);
... ...
Run Code Online (Sandbox Code Playgroud)

我运行相同的 curl 命令,它工作正常!

所以我想知道 app.use 和 app.post 之间的区别。需要您的帮助,非常感谢。

Abh*_*nyu 5

app.use() 用于包含中间件/拦截器函数,该函数将在调用 api 时执行实际函数之前执行。

更多详情请参考-快递官

例如 :

app.use(cors());
    app.post("/",function(req,res){
    });
Run Code Online (Sandbox Code Playgroud)

上面这行代码相当于

app.post("/",cors(),function(req,res){
});
Run Code Online (Sandbox Code Playgroud)

app.post 、 app.get 、 app.put 、 app.delete 定义了 api 的 http 方法。有关 http 方法的更多详细信息,
请参阅链接http://www.tutorialspoint.com/http/http_methods.htm

在你的情况下

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);
}
Run Code Online (Sandbox Code Playgroud)

当 /add_module api 被调用时,首先 bodyParser.json() 然后 bodyParser.urlencoded({ extended: true }) 函数被调用之后

 function(req, res) {
        console.log("Start submitting");
        console.log(req.body);} 
Run Code Online (Sandbox Code Playgroud)

叫做 。bodyParser.json() 和 bodyParse.urlencoded({extended:true}) 需要在被调用的函数(req,res)中从请求中获取正文对象