топор ios expressJS разные файлы - PullRequest
0 голосов
/ 22 апреля 2020

Куда бы я ни посмотрел, у каждого есть топор ios вызов в express вызове. Я не хочу этого делать. У меня есть код для вызова API в другом файле, и я вызываю его с моего маршрутизатора. Я просто не могу понять, как получить доступ к возвращенным данным. Может кто-нибудь помочь, пожалуйста?

Топор ios Звоните:

function weather(geo) {
  let geoLocation = `https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(geo)}.json?access_token=pk.eyJ1IjoiY2FydGVydzIxMjQiLCJhIjoiY2s5NGNlcmY2MDAzaTNncDJwN2ozdWk2byJ9._fm9rvVvhbCJE2eN0C-gqQ&limit=1`
  axios.get(geoLocation)
    .then((response) => {
      if (response.data.features.length === 0) {
        return console.log('Unable to find location')
      } else {
        const long = response.data.features[0].center[1]
        const lat = response.data.features[0].center[0]
        const url = `http://api.weatherstack.com/current?access_key=ebe5b5662c85c2740c00d538723b44b3&query=${long},${lat}&units=f`
        return axios.get(url)
      }
    })
    .then((response) => {
      if (response.data.error) {
        console.log(response.data.error.info)
      } else {
        console.log(response.data)
        let forecastData = response.data;
        return forecastData
      }
    })
    .catch((error) => {
      console.log('Unable to connect to weather service')
    })
}

Express Звоните:

router.get('/help', function (req, res) {
  weather.weather(req.query.address)
  res.send({
    address: req.query.address,
    forecast: '?'
  })
})

1 Ответ

0 голосов
/ 22 апреля 2020

Ваша weather функция является асин c, поэтому вы должны добавить возвращаемое значение для axios вызова:

function weather(geo) {

  let geoLocation = `https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(geo)}.json?access_token=pk.eyJ1IjoiY2FydGVydzIxMjQiLCJhIjoiY2s5NGNlcmY2MDAzaTNncDJwN2ozdWk2byJ9._fm9rvVvhbCJE2eN0C-gqQ&limit=1`
  return axios.get(geoLocation)
    .then((response) => {
      if (response.data.features.length === 0) {
        throw 'Unable to find location'
      } 
      else {
        const long = response.data.features[0].center[1]
        const lat = response.data.features[0].center[0]
        const url = `http://api.weatherstack.com/current?access_key=ebe5b5662c85c2740c00d538723b44b3&query=${long},${lat}&units=f`
        return axios.get(url)
      }
    })
    .then((response) => {
      if (response.data.error) {
        throw response.data.error.info
      } 
      else {
        console.log(response.data)
        let forecastData = response.data;
        return forecastData
      }
    })
    .catch((error) => {
      throw error;
    })
}

и в вашем маршрутизаторе:

router.get('/help', function (req, res) {
  weather.weather(req.query.address)
    .then(res => {
      res.send({
        address: req.query.address,
        forecast: '?'
      })
    })
    .catch(err => {
      console.log(err);
    })

})

Также возвращение console.log не правильно. Просто выбросьте его сообщение и обработайте сообщение в маршрутизаторе:

С

if (response.data.features.length === 0) {
  return console.log('Unable to find location')
}

К

if (response.data.features.length === 0) {
  throw 'Unable to find location'
}
...