Thiago Régis
Thiago Régis

Reputation: 123

Express Router middleware error (`app.use() requires a middleware function`)

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?

Upvotes: 0

Views: 558

Answers (1)

Thiago Régis
Thiago Régis

Reputation: 123

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);

Upvotes: 1

Related Questions