快速处理URIError:无法解码param

时间:2016-03-21 07:24:55

标签: 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。这工作正常,除非有一个格式错误的网址,例如: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)

当用户可以随机查看我的项目文件在服务器中的位置时,这并不好。有办法处理这个错误吗?

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:3)

可能的解决方法:

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

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

// your express error handler
app.use(function(err, req, res, next) {
    // in case of specific URIError
    if (err instanceof URIError) {
        err.message = 'Failed to decode param: ' + req.url;
        err.status = err.statusCode = 400;

        // .. your redirect here if still needed
        return res.redirect(['https://', req.get('Host'), req.url].join(''));
    } else {
        // ..
    }
    // ..
});

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

答案 2 :(得分:0)

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

// handles 400 error
app.use((err, req, res, next) => {
  if (!err) return next();
  return res.status(400).json({
    status: 400,
    error: 'OOps! Bad request',
  });
});

编辑: 该代码段应放置在最后一条路由中,它检查是否存在其他路由跳过的错误(显然存在),并发送默认响应。当您将%添加为API端点的最后一个字符时,就会发生此错误。