1. install express
npm init
npm install --save express
const express = require('express');
const app = express();
for nodemon use it as development dependency
npm install --save-dev nodemon
and in the scripts use start for nodemon app.js
For following MVC way model view and controller
create 2 folders controllers and routers => controllers will have logic after routes are handled
and in routes routing is handled
Under Routes > routes.js
1. use express
then routes = express. router()
const express = require('express');
const router = express.Router();
this router has to be exported as module
module.exports=router;
for defining routes use
router.get('/post',feedcontroller.getpost)
under feed controller => feed.js
create a function for the each routes as diffrent modiles
exports.getPosts=(req,res,next)=>{
res.json(
{posts:[{title:"first post",content:"first post content"}]}
);
}
As it is Api so response is set as Json
router.get('/posts',feedController.getPosts);
in app.js
app.use('/feed',feedrouter);
app.listen(8080);
for parsing incomming request body parser is to be used as json
install it as
npm install --save body-parser
app.use(bodyParser.json());
extracting data from body
exports.createPosts=(req,res,next)=>{
const title = req.body.title;
const content= req.body.content;
res.status(201).json({
message:'Post created',
post:{
id: new Date().toISOString(),
title:title,
content:content}
} );
};