我的 server.js 文件中有这个 Express js 代码:
var express = require('express');
var app = express();
var fs = require('fs');
var publicdir = __dirname + '/client';
app.set('port', 8080);
app.use(function(req, res, next) {
if (req.path.indexOf('/js/') === -1 && req.path.indexOf('/css/') === -1) {
if (req.path.substr(-1) === '/') {
req.url = req.url.slice(0, -1) + '.html';
} else {
res.redirect(301, req.url + '/');
}
}
next();
});
app.use(express.static(publicdir, {
extensions: ['html', 'htm']
}));
我试图使网址呈现一致,以便在每个网址末尾始终有一个尾随“/”。虽然上面的代码有效,但我不断在日志文件中收到错误消息:
错误:发送后无法设置 header 。
此错误来自这样的 url 模式:
http://www.myserver.com/my-page-name
但它确实正确地将尾随“/”添加到末尾。
如何更改上述代码以消除该日志错误?
最佳答案
在调用 res.redirect()
后,请勿调用 next()
,因为这将允许其他路由处理程序处理 URL,从而导致您在两个路由处理程序都尝试发送响应时看到错误消息。
将您的中间件处理程序代码更改为此(保留其余代码不变):
app.use(function(req, res, next) {
if (req.path.indexOf('/js/') === -1 && req.path.indexOf('/css/') === -1) {
if (req.path.substr(-1) === '/') {
req.url = req.url.slice(0, -1) + '.html';
} else {
// redirect to add the slash, do not continue routing
res.redirect(301, req.url + '/');
return; // returning here will skip the call to next() below
// so there will be no additional routing
}
}
// continue routing if we get here
next();
});
我们的想法是,您希望在所有不发出 res.redirect()
的代码路径中调用 next()
,但不在任何发出 res.redirect()
的代码路径中调用。
关于javascript - Express js,将尾随 "/"添加到所有网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46498132/