【问题标题】:Pass data from API to another API nodejs and vanilla Javascript将数据从 API 传递到另一个 API nodejs 和 vanilla Javascript
【发布时间】:2020-08-02 07:47:00
【问题描述】:

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

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

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

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

first hit on button results

second hit on button results

在客户端

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 ** city, Country Name , weather **

【问题讨论】:

  • 但是你没有对发布请求做任何事情。您只是接收请求正文并将相同的内容发送回客户端。这对我来说真的没有意义。您能否再澄清一下流程?
  • @Aviv Lo 我的代码流程是获取用户使用 geonames API 输入的特定城市的纬度、经度和国家名称,然后将此请求中的纬度和经度用作另一个 API 中的参数(watearbit ) - 需要这些数据来完成请求 - 获取城市的当前或预报天气并使用这些信息更新 UI ** city, Country Name , weather **

标签: javascript node.js api pure-js


【解决方案1】:

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

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);
        })

【讨论】:

  • 如果我用硬编码数据替换代码```lat=${weatherData.latitude}```我检查了格式只是``'50.123'```代码工作完美并获得数据如果我控制台记录我得到的 URL(例如:***********/&lat=1234&lon=12345&key=API_KEY),我需要这样做,否则如果我输入 ``` lat=${weatherData.latitude} ``` 我会得到 URL (例如:*************/&lat=1234&lon=12345&key=API_KEY)
  • 如果我删除 API 密钥 api.weatherbit.io/v2.0/forecast/…
  • 没错。这意味着您没有从用户的输入中获得正确的纬度和经度。这就是为什么它说未定义。
  • 用户不输入经纬度。用户只输入城市名称,第一个 API 获取 lat 和 long,并假设将这些作为参数传递给第二个 API
  • 我看不出与我的代码有什么区别,我将编辑 main.js 文件的帖子,请看一下
猜你喜欢
  • 1970-01-01
  • 2018-05-02
  • 1970-01-01
  • 2012-11-09
  • 2022-11-29
  • 2016-10-30
  • 2020-12-19
  • 1970-01-01
  • 2022-11-15
相关资源
最近更新 更多