javascript – 快速路由非ascii字符(波斯语)

我正在尝试使用这条路线
http://localhost:3030/api/words/عشق

在我的快递应用程序中,所以我可以匹配字典中的单词.

浏览器将URL更改为http://localhost:3030/api/words/%D8%B9%D8%B4%D9%82但我编写了一个小型中间件,在将其传递给路由之前将其转换回原始版本.在路由中,我有正则表达式,检查包含波斯语/波斯语字符的unicode字符.

不知道发生了什么,因为中间件打印/ words /عشق,如果我删除正则表达式规则,路由也打印/ words /عشق.为什么快递不符合这个?表示不使用req.url来确定路线吗?

    /** Get word be string **/
    api.get('/:word(^([\\u0600-\\u06FF]+\\s?)+$)', (req, res, next) =>{
            console.log("persian version " + req.url);
            res.send(req.params);
});


 /** Url encoder middleware **/ 
function urlencoder(req, res, next) {
      req.url = decodeURIComponent(req.url); 
      console.log("Middleware " + req.url);
      next();
}

最佳答案 我认为将路径路径转换为正则表达式的代码已经使用锚点(^)为正则表达式添加了前缀,因此您不应在其中使用额外的代码.

这似乎有效:

let unescape = require('querystring').unescape;

api.use((req, res, next) => {
  req.url = unescape(req.url);
  next();
});

api.get('/:word(([\\u0600-\\u06FF]+\\s?)+$)', (req, res) => {
  console.log("persian version " + req.url);
  res.send(req.params);
});
点赞