Express.js导入外部路由中间件后API请求挂起问题求助
Got it, let's troubleshoot why your Postman requests are hanging indefinitely! The root issue is how you're structuring your routes—you're creating a separate Express app instance in your routes file instead of using Express's built-in Router, and your current setup never makes those routes accessible to your main server app.
Here's how to fix it step by step:
1. Update your routes/index.js file
Instead of creating a new express() app, use express.Router() to create a modular route handler. This is the standard way to split routes into separate files in Express:
/* Name: index.js Notes: export routes here */ import express from 'express'; // Create a Router instance (not a full Express app) const router = express.Router(); // Define your route directly on the router router.get('/test', function(req, res) { res.status(200).json({ message: 'Connected!' }); }); // Export the router instance so your main server can use it export default router;
2. Why your original code didn't work
- In your original routes file, you created a brand new Express app (
const app = express();) and defined a route on it—but this app is completely separate from the one inserver.js. Your main server app never gets access to this route, so when you send a request to/test, the main app has no idea how to handle it, leading to hanging requests. - The
Routerobject is designed exactly for this use case: it lets you group routes in separate files, then mount them onto your main Express app.
3. Verify your server.js is good to go
Your existing server.js doesn't need any changes—since you're importing the router and mounting it with app.use('/', routes), the main app will now recognize all routes defined on the router.
Test it out
Restart your server, then send a GET request to http://localhost:5000/test in Postman. You should immediately get the { message: 'Connected!' } response without any hanging.
内容的提问来源于stack exchange,提问作者David Sanders

