Reputation: 1
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"}
]
});
};
Upvotes: 0
Views: 163
Reputation: 39
As both Abhishek and lolmc mentioned res.json({...})
should do the trick. res
is an object with methods. These methods responds to the HTTP request.
res
is short for response.
e.g. res.json({ message: 'This is a test message.' })
to reply to a HTTP request with json.
See this post on stackoverflow where Dave Ward explains req
and res
and read the docs for res and the docs for req to learn more.
Upvotes: 0
Reputation: 380
This can be use inside your controllers/post.js
exports.getPosts= (req,res)=>{
const json = {
posts:
[
{title:"First Post"},
{title:"Second Post"}
]
};
res.send(json);
};
Or use res.json({ ... })
as per @lolmc answer.
More about response for different format -> Express API Ref
Upvotes: 1