2017-12-29 57 views
-1

ここに私のルート定義はExpress.jsである:私が使用しようと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として、一般的なルートにアクセスしようとすると、私のコードは、しかし、正常に動作します

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は横ばい、およびこのエラーを削除するエイリアスを追加する必要はありませんしたいと思います:ルートファイルから、上記で定義された特定のルート、など/webstore/sessionは、私はこのエラーが発生しました。汎用ルートと定義されたルートが衝突するため、Expressがヘッダーを設定できないようにするにはどうすればよいですか?

答えて

1

あなたができない2番目の応答を送信しようとしているためです。 以下の行とその内容を確認してください。

res.send("..."); 

とあなたには、いくつかの他のミドルウェアのルート

res.send("...."); 

あなたがそのエラーを取得するには次の操作を行います。

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

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

は、基本的には、いくつかのルートでこれを持っている場合。

ヘッダーの再送信を防止するために、finalizeメソッドと404/500エラーハンドラに次のコードを追加します。ただし、セッション操作、データベース呼び出しなどがある場合、コードは両方のブランチのすべてのロジックを処理しています。

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

ご迷惑をおかけします。すぐにこの問題を解決しましたが、新年の後に更新するのを忘れていたに違いありません。 – NobleUplift

関連する問題