Express URIError:无法解码参数



当请求的参数包含%时,我将next.js与自定义快速服务器一起使用,这会导致此错误:

URIError: Failed to decode param '%%faker'
at decodeURIComponent (<anonymous>)
at decode_param (D:ahmedcodingreact jswith-redux-appnode_modulesexpresslibrouterlayer.js:172:12)
at Layer.match (D:ahmedcodingreact jswith-redux-appnode_modulesexpresslibrouterlayer.js:148:15)
at matchLayer (D:ahmedcodingreact jswith-redux-appnode_modulesexpresslibrouterindex.js:574:18)
at next (D:ahmedcodingreact jswith-redux-appnode_modulesexpresslibrouterindex.js:220:15)
at middleware (D:ahmedcodingreact jswith-redux-appnode_moduleshttp-proxy-middlewarelibindex.js:43:7)
at Layer.handle [as handle_request] (D:ahmedcodingreact jswith-redux-appnode_modulesexpresslibrouterlayer.js:95:5)
at trim_prefix (D:ahmedcodingreact jswith-redux-appnode_modulesexpresslibrouterindex.js:317:13)
at D:ahmedcodingreact jswith-redux-appnode_modulesexpresslibrouterindex.js:284:7
at Function.process_params (D:ahmedcodingreact jswith-redux-appnode_modulesexpresslibrouterindex.js:335:12)
at next (D:ahmedcodingreact jswith-redux-appnode_modulesexpresslibrouterindex.js:275:10)
at expressInit (D:ahmedcodingreact jswith-redux-appnode_modulesexpresslibmiddlewareinit.js:40:5)
at Layer.handle [as handle_request] (D:ahmedcodingreact jswith-redux-appnode_modulesexpresslibrouterlayer.js:95:5)
at trim_prefix (D:ahmedcodingreact jswith-redux-appnode_modulesexpresslibrouterindex.js:317:13)
at D:ahmedcodingreact jswith-redux-appnode_modulesexpresslibrouterindex.js:284:7
at Function.process_params (D:ahmedcodingreact jswith-redux-appnode_modulesexpresslibrouterindex.js:335:12)

例如,如果请求http://localhost:3000/summoner/eune/%%faker则会发生错误,但如果http://localhost:3000/summoner/eune/^^faker^^被编码,URL 变得http://localhost:3000/summoner/eune/%5E%5Efaker并且一切正常。 快速处理 URIError: 无法像这样解码参数:

server.use((err, req, res, next) => {
if (err instanceof URIError) {
err.message = "Failed to decode param: " + req.url;
err.status = err.statusCode = 400;
console.log(err);
return res.redirect(`http://${req.get("Host")}${req.url}`);
// return app.render(req, res, "/_error");
}
});

return res.redirect(`http://${req.get("Host")}${req.url}`);这会将用户从http://localhost:3000/summoner/eune/%%faker重定向到http://localhost:3000/summoner/eune/%25%25faker,如果我使用return app.render(req, res, "/_error");它会将Next.js提供的默认错误页面发送回用户,但这不是我想要的。我想像^一样处理%.

所以我的问题是:

  1. 为什么%没有编码为%25,如果有办法实现它?
  2. 谁负责对浏览器或快递进行编码?
  3. 处理此错误的最佳方法是什么?

我正在使用节点 v8.9.1,表示 ^4.16.3。 请详细说明答案,我是一名初学者开发人员。 谢谢你的时间。

正如您所指出的,网址是百分比编码的,http://localhost:3000/summoner/eune/%%faker作为网址无效。

当您输入无效的 url 时,大多数浏览器都愿意将其更改为有效内容,例如:http://localhost:3000/test test会自动更改为http://localhost:3000/test%20test,但这只是一个回退,以避免太多错误。

在您的情况下,%不会自动更改为%25,因为浏览器不知道何时替换%以及何时离开它。例如:当您键入%25%25faker时,此 url 应该按原样使用还是应该替换为%2525%2525faker

总结:您必须在任何时间点使用有效的 URL,并且不依赖于浏览器的善意。

最新更新