5

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.

Tyrion
  • 115
  • 1
  • 2
  • 4

2 Answers2

7

app.use() is use to include middleware/interceptor function that will be executed before the actual function will executed when an api is call .

for more details refer - express offcial website

for example :

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

The above line of code is equivalent to

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

app.post , app.get , app.put , app.delete define the http method for the api .
please refer link http://www.tutorialspoint.com/http/http_methods.htm for more details about http methods

In your case

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

when /add_module api is called , first bodyParser.json() then bodyParser.urlencoded({ extended: true }) function is called after that

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

is called . bodyParser.json() and bodyParse.urlencoded({extended:true}) is required get body object from request in the called function(req,res)

Abhimanyu
  • 705
  • 7
  • 20
3

It's the quite the same but :

  • middleware included in app.use will be use in all request

  • middleware included in app.post("/route" will be use only for request of type POST wich match the path /route

Example, if you server contains the following :

 // 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({});
 })

A request GET on /api/test3 will raise the following :

- Middleware1

- Middleware2

- finalGETAction3

A request POST on /api/test1 will raise the following :

- Middleware1

- Middleware2

- Middleware3

- finalPOSTAction1

And a request POST on /api/test2 will raise the following :

- Middleware1

- Middleware2

- Middleware4

- finalPOSTAction2
Daphoque
  • 4,421
  • 1
  • 20
  • 31