0

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"}

            ]
    });
};
James Z
  • 11,838
  • 10
  • 25
  • 41

3 Answers3

1

In controllers/post.js

Try res.json({...}); instead res.json=({...});

Sandeep Kumar
  • 1,707
  • 4
  • 21
  • 31
lolmc
  • 11
  • 2
1

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

Abhishek
  • 362
  • 1
  • 5
  • I get this error: = throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) What does this mean? @Sandeep Kumar – aswathsrimari Dec 21 '19 at 09:43
0

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.