javascript - Express js,将尾随 "/"添加到所有网址

标签 javascript node.js express

我的 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/

相关文章:

c - Visual Studio Express 2015 : Cannot open . exe 文件中出现 LNK1104 错误

javascript - Express.js 路线组织

node.js - 在 Express 的自定义错误处理程序中获取堆栈跟踪?

javascript - 数据属性在 JQuery 中返回未定义

javascript - WebRTC 使用哪种媒体设备

javascript - JS/Node :- Selecting a tag using node. io

php - 发送私有(private)消息或向 socket.io 中的特定用户发送消息的问题

javascript - 如何以反向/从右到左的顺序显示阿拉伯语站点的 nivo-slider 分页?

javascript - 按两次提交后,Ajax 就可以工作了

javascript - 基于 api key 的 Node JS Web 服务