I have just started to learn NodeJS
and I am stuck with this. I am trying to handle the request. The localhost
keeps loading or throws an error
cannot GET/
The JSON
code needs to be displayed on my localhost
site. What changes to routes
or controllers
should I make?
Here is the app.js
file that calls the router to handle the request.
app.js
const express=require("express");
const app=express();
const Postroutes=require('./routes/post');
app.use("/" , Postroutes);
const port=8000;
app.listen(port, ()=>{
console.log(`a node js api is listening on port ${port}`);
});
the routes will forward the request to the controller.
routes/post.js
const express= require("express")
const PostController=require('../controllers/post')
const router=express.Router()
router.get("/",PostController.getPosts);
module.exports= router;
The controller will respond with the JSON.
controllers/post.js
exports.getPosts= (req,res)=>{
res.json=({
posts:
[
{title:"First Post"},
{title:"Second Post"}
]
});
};