Javascript 如何防止常规路由在Express.js中的特定路由中设置标头?

Javascript 如何防止常规路由在Express.js中的特定路由中设置标头?,javascript,node.js,express,routes,http-headers,Javascript,Node.js,Express,Routes,Http Headers,以下是我在Express.js中的路线定义: // Building specific routes defined by a route file routes.use(this.initialize.bind(this)); routes.use(this.isAuthenticated.bind(this)); routes.use(this.isAuthorized.bind(this)); if (Route.METHOD == 'POST') { routes.use(rou

以下是我在Express.js中的路线定义:

// Building specific routes defined by a route file
routes.use(this.initialize.bind(this));
routes.use(this.isAuthenticated.bind(this));
routes.use(this.isAuthorized.bind(this));
if (Route.METHOD == 'POST') {
    routes.use(route.post.bind(route));
} else {
    routes.use(route.get.bind(route));
}
routes.use(this.finalize.bind(this));

router.use('/webstore/' + Route.RESOURCE + (parameters.length != 0 ? '/' : '') + parameters.join('/'), routes);

//router.use('/webstore/session', routes);

// Building generic routes
console.log('Creating GET route: ' + 
            '/:connectionName(webstore|localdatastore)/:objectName');
router.get('/:connectionName(webstore|localdatastore)/:objectName', 
    this.initialize.bind(this), this.isAuthenticated.bind(this), this.isAuthorized.bind(this), this.get.bind(this), this.finalize.bind(this));
console.log('Creating POST route: ' + 
    '/:connectionName(webstore|localdatastore)/:objectName');
router.post('/:connectionName(webstore|localdatastore)/:objectName', 
    this.initialize.bind(this), this.isAuthenticated.bind(this), this.isAuthorized.bind(this), this.get.bind(this), this.finalize.bind(this));
如果我尝试访问上面两行中定义的通用路由,例如
/webstore/user
,我的代码工作正常,但是,如果我尝试使用上面从路由文件定义的特定路由,例如
/webstore/session
,我会收到以下错误:

Error: Can't set headers after they are sent.
    at ServerResponse.setHeader (_http_outgoing.js:371:11)
    at ServerResponse.header (./node_modules/express/lib/response.js:767:10)
    at ServerResponse.contentType (./node_modules/express/lib/response.js:595:15)
    at Server.finalize (./dist/server.js:1156:17)
    at Layer.handle [as handle_request] (./node_modules/express/lib/router/layer.js:95:5)
    ...

我希望我的API保持平坦,不必添加别名来删除此错误。如何防止Express设置标题,因为通用路由和定义路由冲突?

因为您试图发送第二个响应,这是不可能的。 检查以下行及其内容

routes.use(this.finalize.bind(this));

router.use('/webstore/' + Route.RESOURCE + (parameters.length != 0 ? '/' : '') + parameters.join('/'), routes);
基本上,当你在某条路线上有这样的情况时:

res.send("...");
您可以通过其他中间件路径来实现这一点

res.send("....");
你会得到那个错误

将以下代码添加到finalize方法和任何404/500错误处理程序中,以防止再次发送头。但是,如果存在会话操作、数据库调用等,代码仍在处理两个分支中的所有逻辑

if (res.headersSent) {
    return next();
}

很抱歉迟了答复。你让我走上了正确的道路,我很快就解决了这个问题,但一定忘了在新年后更新。