所以我试图将API数据从一个JS文件导入到另一个文件中,但是我一直在得到未定义或错误的提示。我要导入的变量是从weathermap.js到app.js的天气,城市和温度。任何帮助将不胜感激。
这与我从weathermap.js导出的方式或如何导入app.js的方式有关系吗?
#include <cmath>
#include <string>
#include <vector>
#include <iostream>
void my_insert (std::vector<int> const &)
{ }
template <typename T, typename ... As>
void my_insert (std::vector<int> &, std::vector<T> const &, As const & ...);
template <typename T, typename ... As>
void my_insert (std::vector<int> & v, T const & t, As const & ... as)
{
int i{};
if constexpr ( std::is_convertible_v<T, char const *> )
i = std::stoi(t);
else if constexpr ( std::is_same_v<T, char> )
i = t - 48;
else if constexpr ( std::is_same_v<T, int> )
i = t;
else if constexpr ( std::is_same_v<T, double> )
i = static_cast<int>(std::round(t));
else if constexpr ( std::is_same_v<T, bool> )
i = t;
// else ???
v.push_back(i);
my_insert(v, as...);
}
template <typename T, typename ... As>
void my_insert (std::vector<int> & v, std::vector<T> const & t,
As const & ... as)
{
for ( auto const & val : t )
my_insert(v, val);
my_insert(v, as...);
}
int main ()
{
std::vector<int> v;
std::vector<char> u { '9', '8', '7' };
my_insert(v, "123", "-8", 32, 3.14159, true, u, false, '5', "12.3");
for ( auto const & val : v )
std::cout << val << ' ';
std::cout << std::endl;
}
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");
})
答案 0 :(得分:0)
由于要在weathermap.js文件中调用异步API,因此无法定义。它将等待请求完成。因此,请使用 async / await或Promise 。然后回调以等待api完成调用。
答案 1 :(得分:0)
在天气图响应数据返回函数调用和返回之前,这就是为什么未定义的原因。 您可以在功能中设置异步或承诺。