【问题标题】:Importing API Values from one JS into another NODEjs将 API 值从一个 JS 导入另一个 NODEjs
【发布时间】:2020-03-31 09:30:21
【问题描述】:

所以我试图将 API 数据从一个 JS 文件导入到另一个文件中,但我不断收到未定义或只是错误。我要导入的变量是 Weathermap.js 中的 Weather、City 和 Temperature 到 app.js 中。任何帮助将不胜感激。

这与我如何从 weathermap.js 导出或如何导入 app.js 有关吗??


app.js

const express = require("express");
const path = require("path");
const hbs = require('hbs');
const myForecast = require('./weathermap');
var appweather = myForecast.weather;
var appcity = myForecast.city;
var apptemperature = myForecast.temperature;


// This actually makes express run in our file
const app = express();
const publicDirectory = path.join(__dirname, "../public");
const viewsPath = path.join(__dirname, '../templates/views');
const partialPath = path.join(__dirname, '../templates/partials');
hbs.registerPartials(partialPath);


// console.log("This is the variable info: ", weather, city, temperature)
myForecast("Manchester", "uk", "metric");



app.use(express.static(publicDirectory));

app.set('view engine', 'hbs');
app.set('views', viewsPath);

// var weather = require('./weathermap.js').weather;
// var city = require('./weathermap.js').city;
// var temperature = require('./weathermap.js').temperature;

app.get("/", (req, res) => {    
    // console.log(myForecast.city);
    res.render("index", {
        title: 'Weather App',
        author: 'Frazer MacRostie',
        city: appcity,
        weather: appweather,
        temperature: apptemperature
    });
});

// app.get("")

app.get("/about", (req, res) => {    
    res.render("about", {
    });
});

app.get('*', (req, res) => {
    res.send('<h1>404 your page does not exist</h1>')
})

// console.log(__dirname);
// console.log(__filename);

app.listen(3000, ()=>{
    console.log(myForecast.city);
    console.log("Server is running on localhost 3000");
})

weathermap.js


const request = require('request');
var weather = "";
var city = "";
var temperature = "";


const forecast = (city, country, units) => {

    const encodedCityName = encodeURIComponent(city);
    const encodedCountryName = encodeURIComponent(country);

    const weatherMapUrl = `http://api.openweathermap.org/data/2.5/weather?q=${encodedCityName},${encodedCountryName}&units=${units}&APPID=4fe147c8dc2f848fd447182ebd444e80`

    request({ url: weatherMapUrl, json: true }, (error, response) => {
        // console.log(response.body);

        weather = `${response.body.weather[0].main}`
        city = `${response.body.name}`
        temperature = `${response.body.main.temp}`
        console.log(weather, city, temperature)

        if(error) {
            console.log("ERROR! Cannot connect to the API services.")
        } else if (city === undefined){
            console.log("I'm sorry, that City does not exist.")
        } else{
            console.log(`Today we have mainly ${weather}`)

            console.log(`The current temperature in ${city} is ${temperature}°C`)
        }
        return weather + city + temperature;


    })
}

// module.exports = weather;
// module.exports = city;
// module.exports = temperature;
module.exports = forecast;

// exports.forecast = () => {
//     return weather + city + temperature;
//   };


// &units=metric
// &units=imperial

【问题讨论】:

    标签: javascript node.js api


    【解决方案1】:

    在您的天气图响应数据返回函数调用和返回之前,这就是为什么会变得未定义。 您可以在函数中设置 async 或 promise

    【讨论】:

      【解决方案2】:

      因为您正在调用 weathermap.js 文件中的异步 API,所以您会变得未定义。它将等待请求完成。所以使用 async/await 或 Promise .then 回调等待 api 完成调用。

      【讨论】:

        猜你喜欢
        • 2022-06-17
        • 2015-08-15
        • 1970-01-01
        • 2021-12-10
        • 2023-03-08
        • 2021-07-05
        • 2018-06-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多