You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Express Router处理文件上传时路由未触发的问题排查

问题原因及解决方案

问题核心在于路由导入与使用的方式不匹配:

你的TestRouter.js导出的是一个返回Express.Router实例的函数wrapper,但在index.js中直接将这个函数传给了app.use(),没有执行它生成实际的路由实例。Express无法识别普通函数作为路由中间件,因此TestRouter的逻辑根本没被加载生效。

修复方案(二选一即可)

方案1:在index.js中执行路由函数

修改index.js里路由导入和使用的代码,执行函数生成路由实例:

import Express from 'express';
import fileUpload from 'express-fileupload';
import http from 'http';
import TestRouter from "./TestRouter.js";
let app = new Express();
let httpServer = http.createServer(app);

app.use(Express.json());
app.use(fileUpload({debug:true}));
// 执行函数生成可用的路由实例
const testRouterInstance = TestRouter();
app.use('/test', testRouterInstance);
let portNo=8080;
httpServer.listen(portNo, () => {
    console.log('Express server is running on localhost:'+portNo);
})

方案2:修改TestRouter.js直接导出路由实例

如果不需要函数包裹的额外逻辑,直接导出Router实例即可:

import Express from 'express';
const router = Express.Router();
router.post('/:action', async (req, res, next) => {
    console.log(req.params.action);
    switch (req.params.action) {
        case "uploadFile":
            console.log("hi");
            res.status(200).end();
            break
        default:
            next();
            break
    }
});
export default router;

此时index.js里原来的app.use('/test', TestRouter)就能正常触发路由逻辑了。

内容的提问来源于stack exchange,提问作者The KNVB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 23:55:19