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

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

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

app.get('/weather', (req, res) => {
  const weatherCity = (req.query.weatherCity)
  let decodeURI = decodeURIComponent(weatherCity) //<------- trying to decode the query
  request(weatherURL(decodeURI), function (error, response, body) {
    if (error) {
      throw error
    }
    const data = JSON.parse(body)
    return res.send(data)
  });
})

function weatherURL(weatherCity){
  return `https://api.openweathermap.org/data/2.5/weather?q=${weatherCity}&units=metric&appid=${process.env.APIKEY}&lang=en`
}
ki0zmccv

ki0zmccv1#

这可能是您需要的:

app.get('/weather', (req, res) => {
  const weatherCity = req.query.weatherCity;
  request(weatherURL(weatherCity), function (error, response, body) {
    if (error) {
      throw error
    }
    const data = JSON.parse(body)
    return res.send(data)
  });
})

function weatherURL(weatherCity){
  return `https://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(weatherCity)}&units=metric&appid=${process.env.APIKEY}&lang=en`
}

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

相关问题