NodeJS / Express: what is “app.use”?
In the docs for the NodeJSexpress
module, the example code has app.use(...)
. What is the
use
function and
where is it defined?--question from stack overflow--
Answer:-
According to the Node and express there is something called middleware functions.That means that functions have to access to the request and response objects in the application.Using this middleware functions can execute any code,end the request and response life cycle and also can all to the next middleware.I explain this concept using following example.
books.js
const mongoose=require('mongoose');
const user=mongoose.Schema;
let users=new user({
title:{
type:String
},
auther:{
type:String
}
});
module.exports=mongoose.model('users',users);
book.js
const express=require('express');
const mongoose=require('mongoose');
const cors=require('cors');
const app=express();
const bodyParser=require('body-parser');
const todoRouts=express.Router();
app.use(bodyParser.json());
app.use(cors());
let todo=require('./books');
mongoose.connect('mongodb://127.0.0.1:27017/order',{useNewUrlParser:true})
const connection=mongoose.connection;
connection.once('open',function(){
console.log('connected');
})
todoRouts.route('/add').post(function(req,res){
let to=new todo(req.body);
to.save().then(to=>{
res.status(200).json({'todo':'succsessfully'});
}).catch(err=>{
res.status(400).send('fail');
})
})
app.use('/todo',todoRouts)
app.listen(3000,function(){
console.log('server connect');
})
According to this example,
const app=express() represents the create and object using express.
const todoRouts=express.Router() use to create an object with routing the books.js
class to get its defined schema.
app.use() function specify the middleware function.Things that inside the app.use()
load that things before the get,post and other http requests.
app.use(bodyParser.json()) , app.use(cors()) and app.use('/todo',todoRouts)
These parts load before.
When we use Postman to run this application we need to type url as http://localhost:3000/todo/add