1252748 1252748 - 1 year ago 78
Node.js Question

Express router.get fails, yet app.get works

While walking through this tutorial, I came across a problem wherein the router methods would not work. Using

npm start
and accessing localhost:3000/api/puppies gets a 404 error. However when I changed

var router = express.Router();
router.get('/api/puppies', db.getAllPuppies);


var app = express();
app.get('/api/puppies', db.getAllPuppies);

and run with
node index.js
, the data prints as expected. I've tried also putting at the beginning of my file

app.use(express.static(__dirname + '/api/'));

but no joy. Is this something to do with
npm start
? At one point I literally copy/pasted the code out of the tutorial and still I get the 404s.

Answer Source

A router has to be connected to your express app in order to be part of your server.


Or, more commonly with a path that isolates that router's effect to just URLs that start with a specific path and the router's own URLs are relative to this path:

app.use('/somePath', yourRouter);

Without this, it's just a declared and configured router that isn't attached to any server.

Express documentation examples here.

The tutorial you reference does not appear to show this part of using a router.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download