首页 > 解决方案 > 将数据从 API 传递到另一个 API nodejs 和 vanilla Javascript

问题描述

我正在使用 geonames API 并通过发布请求从中获取数据。现在我想获取这些数据的一部分(纬度,经度)并通过另一个 API(weatherbit API)传递它,因为我的项目需要在 URL 中传递(纬度和经度)并从中获取数据我尝试发出获取请求服务器端获取信息和安全 api 密钥,但它给了我undefined. 代码给了我undefinedURL 参数

(例如https://api.weatherbit.io/v2.0/forecast/daily/&lat=undefined&lon=undefined&key=API_KEY

这是我的代码我该怎么做?

编辑:如果我再次按下按钮,请求工作正常。所以我必须按两次按钮才能从第一个 API 获取经纬度数据。如何解决>

第一次点击按钮结果

第二次点击按钮结果

在客户端

const getWeatherIoURL = async (url) => {
  const response = await fetch(url);
  try {
    const data = await response.text();
    //console.log(data);
    return data;
  } catch (error) {
    console.error(error);
  }
};
export default getWeatherIoURL;

我在服务器端的代码用于发布请求和获取请求

weatherData = {}
app.post('/geoNamesData', (request, response) => {
  weatherData['date'] = new Date();
  weatherData['countryName'] = request.body.countryName;
  weatherData['latitude'] = request.body.latitude;
  weatherData['longitude'] = request.body.longitude;
  response.send(weatherData);
});

//console.log(`your api is: ${process.env.API_WEATHER_KEY}`);

app.get('/weatherURL', (request, respond) => {
  const url_forecast = 'https://api.weatherbit.io/v2.0/forecast/daily';
  const lat = `lat=${weatherData.latitude}`;
  const long = `lon=${weatherData.longitude}`;
  const url = `${url_forecast}?${lat}&${long}&key=${process.env.API_WEATHER_KEY}`;
  console.log(url);

  respond.send(url);
});

我的代码结构

import geoNamesData from './geoNames_data';
import getWeatherIoURL from './weather_bit';
import postData from './post_geoNames';
//import exposeWeatherIoForecast from './weather_bit'

export function main() {
  document.getElementById('search').addEventListener('click', (event) => {
    event.preventDefault();
    const baseURL = 'http://api.geonames.org/searchJSON?q=';
    const API_Credentials = '&username=*********';
    const destination = document.querySelector('#destination').value;


    geoNamesData(baseURL, destination, API_Credentials).then((data) => {
        //console.log(data);
        postData('/geoNamesData', {
          date: new Date(),
          countryName: data.countryName,
          latitude: data.lat,
          longitude: data.lng,
        });
      });
      getWeatherIoURL('/weatherURL').then((data) => {
        console.log(data);
        exposeWeatherIoForecast(data);
      });
 }


我的代码流程是获取用户使用 geonames API 输入的特定城市的纬度、经度和国家名称,然后使用来自该请求的纬度和经度作为另一个 API(watearbit)中的参数 - 这需要这些数据来完成请求 -获取城市的当前或预测天气并使用这些信息更新 UI ** 城市、国家名称、天气 **

标签: javascriptnode.jsapipure-js

解决方案


也许在调用它们之前将您的函数表达式放在顶部。函数声明会被提升,而表达式不会。

const geoNamesData = async (url, destination, api) => {
  const response = await fetch(url + destination + api);
  try {
    const data = await response.json();
    console.log(data.geonames[0]);
    return data.geonames[0];
  } catch (error) {
    console.error(error);
  }
};

const getWeatherIoURL = async (url) => {
  const response = await fetch(url);
  try {
    const data = await response.text();
    //console.log(data);
    return data;
  } catch (error) {
    console.error(error);
  }
};

geoNamesData(baseURL, destination, API_Credentials)
        .then((data) => {
          //console.log(data);
          postData('/geoNamesData', {
            date: new Date(),
            countryName: data.countryName,
            latitude: data.lat,
            longitude: data.lng,
          });
        })

      getWeatherIoURL('/weatherURL')
        .then(data=>{
          console.log(data)
          exposeWeatherIoForecast(data);
        })

推荐阅读