Express js 4 routing directly using function pointer from other file returns 404

Viewed 36

This seems like it should be so simple. The functions to handle the routes are in a separate file. However after requiring that file and passing the function pointer to the app.get it returns a 404 instead.

I have a simple file that exports an object with the function as a key.

src/controllers/Block.js

module.exports = {
  getBlocks: (req, res, next, body) => {
    res.send('blocks')
  }
}

Then in the index file I create a basic Express app and import that Blocks.js file. I use the getBlocks function for the /blocks route.

src/index.js

const express = require('express')
const block = require('./controllers/Block')

const app = express()
const serverPort = 3000;
app.get('/blocks', block.getBlocks)
app.get('/home', (req, res) => {
  res.send('home')
})

app.listen(serverPort, function () {
  console.log('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort);
});

So while block.getBlocks is clearly a function it still returns a 404 when you visit localhost:3000/blocks. However when you visit localhost:3000/home it renders "home" as you would expect.

What on earth am I missing here?

1 Answers

Ok I installed this locally and played around and this made it work:

src/controllers/Block.js

module.exports = {
  getBlocks: (req, res) => {
    res.send('blocks')
  }
}

Removing the body argument. I am unable to explain this tho.

Related