特殊字符在nodejs express中编码如何解码?

58wvjzkj  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(418)

我尝试按照这些指令进行操作,但无法解码uri。我该怎么办?
当我进入一个像这样的城市 http://localhost:5000/weather?weatherCity=Malmö url将更改为此 http://localhost:5000/weather?weatherCity=Malm%C3%B6 ,我如何解码最后一部分,我做错了什么?

  1. app.get('/weather', (req, res) => {
  2. const weatherCity = (req.query.weatherCity)
  3. let decodeURI = decodeURIComponent(weatherCity) //<------- trying to decode the query
  4. request(weatherURL(decodeURI), function (error, response, body) {
  5. if (error) {
  6. throw error
  7. }
  8. const data = JSON.parse(body)
  9. return res.send(data)
  10. });
  11. })
  12. function weatherURL(weatherCity){
  13. return `https://api.openweathermap.org/data/2.5/weather?q=${weatherCity}&units=metric&appid=${process.env.APIKEY}&lang=en`
  14. }
ki0zmccv

ki0zmccv1#

这可能是您需要的:

  1. app.get('/weather', (req, res) => {
  2. const weatherCity = req.query.weatherCity;
  3. request(weatherURL(weatherCity), function (error, response, body) {
  4. if (error) {
  5. throw error
  6. }
  7. const data = JSON.parse(body)
  8. return res.send(data)
  9. });
  10. })
  11. function weatherURL(weatherCity){
  12. return `https://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(weatherCity)}&units=metric&appid=${process.env.APIKEY}&lang=en`
  13. }

应该不需要解码 req.query.weatherCity 因为express会自动执行此操作。
在使用weathercity创建url之前,您确实需要对其进行编码。url查询参数应为url编码。
考虑使用别的东西 request 因为它已被弃用,不支持承诺。 node-fetchaxios ,以及其他,都是不错的选择。

展开查看全部

相关问题