Jon Snow
Jon Snow

Reputation: 13

Express router.route: 404 Error

The first route is working fine, but I get a 404 when I send a request for the second route.

Sending a GET request to http://localhost:3000/api/posts/ returns:

  {
    message: "TODO return all posts"
  }

But sending a GET request to http://localhost:3000/api/posts/1234 returns:

404
Error: Not Found

Am I missing something?

var express = require('express');
var router = express.Router();


router.route('/posts')
  //returns all posts
  .get(function(req, res) {
    res.send({message: 'TODO return all posts'});
  })

  .post(function(req, res) {
      res.send({message: 'TODO Create a new post'});
  });

router.route('/posts/:id')
  //returns a particular post
  .get(function(req, res) {
    res.send({message: 'TODO return post with ID ' + req.params.id})
  })

  //update existing post
  .put(function(req, res) {
    res.send({message: 'TODO modify post with ID ' + req.params.id})
  })

  //delete existing post
  .delete(function(req, res) {
    res.send({message: 'TODO delete post with ID ' + req.params.id})
  });

module.exports = router;

Upvotes: 0

Views: 327

Answers (1)

Ben Nyberg
Ben Nyberg

Reputation: 952

Not sure if this is a typo, but wouldn't the URL be localhost:3000/posts/1234, not localhost:3000/index/posts/1234?

Upvotes: 1

Related Questions