what's the different between app.post and app.use in nodes express?
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)
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