node.js - 快速处理 URIError : Failed to decode param

标签 node.js express

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');
});

关于node.js - 快速处理 URIError : Failed to decode param,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36125216/

相关文章:

javascript - Sequelize : Error trying to nested association

jquery - 有没有办法选择 cheerio 中的每个元素?

javascript - 在 NodeJS 中使用相同的参数在回调函数中调用父函数

javascript - 如何避免在特定 Express 路线上创建 session ?

node.js - 对于简单的代码示例,我应该使用哪种快速模板引擎?

android - Appium 服务器在运行测试时检测平台版本错误

javascript - 检查数组是否包含javascript中的null以外的内容?

node.js - 在后端有条件地更新/删除文档。我是不是该?我是否分配 PUT、POST 或 DELETE http 方法?

javascript - Express,如何从html中获取值

javascript - URL 中带有动态参数的快速路由