Node.js - Express special characters in routes (/campañas)

£可爱£侵袭症+ 提交于 2019-12-17 19:45:02

问题


I have a problem trying to set a route in Node JS with Express framework.

My route is this one:

app.get('/campaña/nueva', sms.nueva);

But i cant get it to work, because of the evil "Ñ" (it works with an "N" tho)

I used codeigniter for a while, and you can set what characters you want to enable or disable Do you guys knows of any workarround or way to enable it in node?


回答1:


I think you'll need to handle both a URL-encoded and perhaps a UTF-8 (and possibly Latin-1 also) variant. Check the following:

  1. How are your clients (browsers) sending the URL?

    • URL encoded as %C3%B1 ?
      • chrome and firefox send the %C3%B1 encoding
      • I would presume this is the dominant and compliant behavior
    • Unicode ?
      • I tested with curl and it looks to send a single character which I presume is just whatever encoding it got from my terminal, which is probably UTF-8.
  2. Based on that, try adjusting your route. You could use a regex or an explicit list

.

app.get('/campaña/nueva', sms.nueva)
app.get('/campa%c3%b1a/nueva', sms.nueva)
//Or for convenience if you like
app.get('/' + encodeURIComponent('campaña') + '/nueva', sms.nueva) 

My guess is ultimately most browsers are going to send the URL-encoded versions, so you can probably get by with just that last version.




回答2:


I ran into the same problem with $ in my route. URL encoded character doesn't work in my case, but escaped one works.

So I ended up with

app.get('/\\$myRoute', function (req, res) {

}


来源:https://stackoverflow.com/questions/15313238/node-js-express-special-characters-in-routes-campa%c3%b1as

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!