【问题标题】:what's the different between app.post and app.use in nodes express?node express 中的 app.post 和 app.use 有什么区别?
【发布时间】:2015-02-14 19:22:39
【问题描述】:

我使用命令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
在 Object.parse(本机)
在 Object.app.post.res.send.error [作为句柄] (/home/xtec/Documents/xtec-simict/sim/app.js:80:21)
在 next_layer (/home/xtec/Documents/xtec-simict/sim/node_modules/express/lib/router/route.js:103:13)
在 Route.dispatch (/home/xtec/Documents/xtec-simict/sim/node_modules/express/lib/router/route.js:107:5)
在 /home/xtec/Documents/xtec-simict/sim/node_modules/express/lib/router/index.js:205:24
在 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)
在 next_layer (/home/xtec/Documents/xtec-simict/sim/node_modules/express/lib/router/route.js:77:14)
在 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);
... ...

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

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

【问题讨论】:

    标签: javascript node.js curl express


    【解决方案1】:

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

    更多详情请参考-快递官方website

    例如:

    app.use(cors());
        app.post("/",function(req,res){
        });
    

    上面这行代码等价于

    app.post("/",cors(),function(req,res){
    });
    

    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);
    }
    

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

     function(req, res) {
            console.log("Start submitting");
            console.log(req.body);} 
    

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

    【讨论】:

      【解决方案2】:

      其实是一样的,但是:

      • app.use 中包含的中间件将在所有请求中使用

      • app.post("/route" 中包含的中间件将仅用于与路径 /route 匹配的 POST 类型的请求

      例如,如果您的服务器包含以下内容:

       // Common middleware
       app.use(function(req, res, next){
          console.log("Middleware1");
          return next();
       });
       app.use(function(req, res, next){
          console.log("Middleware2");
          return next();
       });
      
       // POST middleware
       app.post("/api/test1", function(req, res, next){
          console.log("Middleware3");
          return next();
       })
       app.post("/api/test2", function(req, res, next){
          console.log("Middleware4");
          return next();
       })
      
      
       // Actions
       app.post("/api/test1", function(req, res, next){
          console.log("finalPOSTAction1");
          return res.status(200).json({});
       })
       app.post("/api/test2", function(req, res, next){
         console.log("finalPOSTAction2");
         return res.status(200).json({});
       })
       app.get("/api/test3", function(req, res, next){
         console.log("finalGETAction3");
         return res.status(200).json({});
       })
      

      /api/test3 上的 GET 请求将引发以下问题:

      - Middleware1
      
      - Middleware2
      
      - finalGETAction3
      

      /api/test1 上的请求 POST 将引发以下内容:

      - Middleware1
      
      - Middleware2
      
      - Middleware3
      
      - finalPOSTAction1
      

      在 /api/test2 上的请求 POST 将引发以下内容:

      - Middleware1
      
      - Middleware2
      
      - Middleware4
      
      - finalPOSTAction2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-29
        • 2015-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-28
        相关资源
        最近更新 更多