Express JS Routers


#1

Hi there can you tell me what I’m doing wrong here. Here is my code

     var express = require("express");
     var app = express();**`
     var port = process.env.PORT || 8081;

    //Router
      var bookRouter = express.Router();

      bookRouter.route('/books')
         .get(function(req,res){
              var responseJson = {hello:"This is my api"};
             res.json(responseJson);
          });
      app.use('/api', bookRouter);


      app.get("/", function(req, res) {
          res.send("welcome to this API");
      });

      app.listen(port, function() {
     console.log('Gulp is running my app on PORT:' + port);
      });

I have the following error message:
/home/ubuntu/workspace/app.js:10
bookRouter.route(’/Books’)
^

TypeError: Cannot read property ‘route’ of undefined
at Object. (/home/ubuntu/workspace/app.js:10:11)
at Module._compile (module.js:434:26)
at Object.Module._extensions…js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:475:10)
at startup (node.js:117:18)
at node.js:951:3

Can you help me please.
Many thanks


#2

The problem here is that there is no route function. In this case, the simple fix is to replace this:

 bookRouter.route('/books')
         .get(function(req,res){
              var responseJson = {hello:"This is my api"};
             res.json(responseJson);
          });

With this:

 bookRouter.get('/books', function(req,res){
              var responseJson = {hello:"This is my api"};
             res.json(responseJson);
          });

This says, “for any GET requests to /books, run this function”


#3

Thank you! I will try that