Express报错Router.use()需回调函数却获[object Object]求助
Hey there, let's get this routing error sorted out for you! That error pops up because the way older Express versions handled routing doesn't match how modern Express (4.x+) works, and your code is following the old tutorial's pattern which clashes with the version you're running.
Here's what's going wrong:
Your ./users/routes.js is probably exporting a function that expects an app object (like the old Express 3.x style), but modern Express expects route modules to export an Express Router instance instead. When you try to use that old-style function with app.use(), Express sees an object it can't handle, hence the error.
Step 1: Update your user routes file (./users/routes.js)
Replace whatever's there with this modern Router-based pattern:
const express = require('express'); const router = express.Router(); // Define your user routes here (note the paths are relative to where we'll mount this router) router.get('/', (req, res) => { res.send('List of all users'); }); router.get('/:id', (req, res) => { res.send(`User details for ID: ${req.params.id}`); }); // Export the Router instance module.exports = router;
Step 2: Fix your main routes file (src/server/routes.js)
Instead of treating usersRoutes as a function to call, mount it to a base path using app.use():
const usersRoutes = require('./users/routes'); module.exports = function routes(app) { // Mount the user routes under the /users path app.use('/users', usersRoutes); // Add other route mounts here as needed };
Why this works:
Modern Express uses Router instances to create modular, mountable route handlers. By exporting a Router from your user routes file, you're giving Express a valid callback-compatible object that app.use() can process. The old tutorial's method directly modified the app object, which is no longer the recommended (or compatible) approach in newer versions.
Once you make these changes, restart your Express server and test the /users endpoints—this error should be gone!
内容的提问来源于stack exchange,提问作者VapeKop

