var express = require('express');
var app = express();

app.get('*', function (req, res) {
    var host = req.get('Host');
    return res.redirect(['https://', host, req.url].join(''));
});

var server = app.listen(8080, function () {
  console.log('starting');
});

我有一个简单的脚本,可将http重定向到https。除URL格式错误(例如:website.com/%c0%ae%c0%ae)外,此方法都可以正常工作。它显示如下:
URIError: Failed to decode param '/%c0%ae%c0%ae'
   at decodeURIComponent (native)
   at decode_param (/...<PROJECT DIRECTORY>.../node_modules/express/lib/router/layer.js:167:12)
   at Layer.match (/.../node_modules/express/lib/router/layer.js:143:15)
   at matchLayer (/.../node_modules/express/lib/router/index.js:557:18)
   at next (/.../node_modules/express/lib/router/index.js:216:15)
   at expressInit (/.../node_modules/express/lib/middleware/init.js:33:5)
   at Layer.handle [as handle_request] (/.../node_modules/express/lib/router/layer.js:95:5)
   at trim_prefix (/.../node_modules/express/lib/router/index.js:312:13)
   at /.../node_modules/express/lib/router/index.js:280:7
   at Function.process_params (/.../node_modules/express/lib/router/index.js:330:12)

当用户可以随机查看我的项目文件在服务器中的位置时,这不是很好。有什么办法可以解决这个错误?

最佳答案

感谢@Oleg的提示。但是不知何故,您的解决方案并没有为我记录错误。这是我想出的:

var express = require('express');
var app = express();

app.use(function(req, res, next) {
    var err = null;
    try {
        decodeURIComponent(req.path)
    }
    catch(e) {
        err = e;
    }
    if (err){
        console.log(err, req.url);
        return res.redirect(['https://', req.get('Host'), '/404'].join(''));
    }
    next();
});

app.get('*', function (req, res) {
    return res.redirect(['https://', req.get('Host'), req.url].join(''));
});

var server = app.listen(8080, function () {
    console.log('Starting');
});

09-27 19:19