Search code examples
node.jsexpressmorgan

Node and Express Routing - 404 error


I'm getting back 404 error using nodemon and not quite sure where the problem is. Any tips / resources appreciated!

project root

$ curl http://127.0.0.1:3000/v1/protected
Cannot GET /v1/protected

nodemon: "GET /v1/protected/ HTTP/1.1" 404 26 "-" "curl/7.49.1"

index.js

var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var app = express();

var router = require('./services/router');

mongoose.connect('mongodb://localhost:introToBackend/introToBackend');

app.use(morgan('combined'));
app.use(bodyParser.json());
app.use(express('/v1', router));

const PORT = process.env.PORT || 3000;
var HOST = process.env.HOST || '127.0.0.1';

console.log('Listening on', HOST, PORT);
app.listen(PORT, HOST);

services/router.js

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

function protectedRoute(req, res, next) {
  res.send("The secret!");
}

router.route('/protected')
  .get(protectedRoute);

module.exports = router;

Solution

  • Try writing express.use('/v1',yourRouter); You do not need the express inside app.use