将 API 值从一个 JS 导入到另一个 NODEjs 中



所以我正在尝试将API数据从一个JS文件导入另一个JS文件,但我不断得到未定义或只是错误。我尝试导入的变量是天气图.js城市和温度.js从天气图导入到应用程序中。任何帮助将不胜感激。

这与我如何从天气图导出有关.js还是如何导入应用程序.js??


应用.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");
})

天气图.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

由于您正在天气图.js文件中调用异步 API,因此您正在未定义。这将等待请求完成。所以使用async/await 或 Promise.then 回调来等待 api 完成调用。

在你的天气图响应数据返回函数调用和返回之前,这就是为什么被定义。 您可以在函数中设置异步或承诺

最新更新