Node.js中使用Express.js拆分路由至不同JS文件是否可行?
Problem Statement
I have two separate files: file1.js and file2.js (I think you might have a typo in your original question where you wrote file1.js twice), and I want to handle requests using Express.js. The code in file1.js looks like this:
var express = require('express'); var app = express(); app.get('/foo/bar1', (req, res) => res.json(['bar1']));
I’m curious if I can write this code in file2.js to define a different endpoint:
var express = require('express'); var app = express(); app.get('/foo/bar2', (req, res) => res.json(['bar2']));
Will this setup cause any problems with Express?
Answer
Hey there! That approach will definitely lead to issues, and here’s why:
Every time you call express() in a file, you’re spinning up an entirely separate Express application instance. If you try to start both instances (by calling app.listen() in each file), you’ll run into a port conflict—you can’t have two servers listening on the same port. Even if you use different ports, your routes will be split across two independent servers, which is almost certainly not what you’re aiming for.
The right way to split routes across multiple files is to use Express’s Router module, which lets you create modular, mountable route handlers. Here’s how to fix your code:
- Refactor
file1.jsto use a Router:
var express = require('express'); var router = express.Router(); // Define the route relative to the path we'll mount it on router.get('/bar1', (req, res) => res.json(['bar1'])); module.exports = router;
- Update
file2.jsthe same way:
var express = require('express'); var router = express.Router(); router.get('/bar2', (req, res) => res.json(['bar2'])); module.exports = router;
- Create a main entry file (like
app.js) to mount both routers:
var express = require('express'); var app = express(); // Import your route modules const bar1Routes = require('./file1'); const bar2Routes = require('./file2'); // Mount both routers under the `/foo` base path app.use('/foo', bar1Routes); app.use('/foo', bar2Routes); // Start your server app.listen(3000, () => { console.log('Server up and running on port 3000!'); });
With this setup, both /foo/bar1 and /foo/bar2 routes will live on the same Express server, and you’ll get clean, organized code without any conflicts.
内容的提问来源于stack exchange,提问作者hitwill

