0

I know there are many similar questions here, but I promise I've read all of them and didn't find a solution.

I'm trying to write an app using Express Router, but I'm getting this error:

app.use() requires a middleware function

I already tried to implement the middleware in many ways, but couldn't fix.

Here's the latest version of my code (which is very neat):

/index.js

import express from 'express';

const app = express();

app.use((req, res, next) => {
  console.log(req.method, req.url);
  next();
});

app.use(require('./routes'));

/routes/index.js

import credentials from './credentials';

export default [credentials];

/routes/credentials/index.js

import express from 'express';

const router = express.Router();

router.get('/credentials', async (req, res) => {
    console.log('Getting credentials...');
});

export default router;

Can anybody help me find the issue?

5
  • 1
    In routes/index file you're exporting an array having credentials as one item, but app.use is expecting a middleware function Commented Dec 26, 2018 at 2:07
  • @AbhaySehgal I'm actually passing an array to be added in app.use of my index. When I require directly /routes/credentials/index.js I get this error: Router.use() requires a middleware function but got a Object. Commented Dec 26, 2018 at 2:16
  • I think that's because nodejs use commonjs so you require to use module.export instead of export default Commented Dec 26, 2018 at 2:24
  • Replace export default router with module.export = router Commented Dec 26, 2018 at 2:24
  • @AbhaySehgal I just answered my own question: stackoverflow.com/a/53927036/3799550. Thanks for your time anyways. Commented Dec 26, 2018 at 3:05

1 Answer 1

1

I found the error. In my /index.js, I should have added my routes into a router.use instead of app.use.

Here's the final code of my /index.js:

import express from 'express';

const app = express();
const router = express.Router();

router.use(require('./routes'));
app.use(router);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.