如何使从API接收的数据全局可访问?



我应该在代码中做些什么更改,以便我可以在dataset = {};中存储天气预报数据,或者我可以做些什么来使预报数据全局可访问?

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
const https = require("https");
const { json } = require("express/lib/response");
const fetch = require('node-fetch');
var _ = require('lodash');
// const unixconvertor = require("./functions");
app.set('view engine', 'ejs');
// const convertor = require(__dirname + "/functions.js");
// const coordinates = [{lat:18.521428 , lon:73.8544541}]
let dataset = {};

app.get("/", function (req, res) {
let pagename = "";
res.render("index",{pagename:pagename});
})
//reminder:add code which gives user choice to choose between unit 
app.post("/", function (req, res) {
let cityname = req.body.city;        // get data  
const appid = "xxxxxxxxxx";
let coordinatelink = "http://api.openweathermap.org/geo/1.0/direct?q=" + cityname + "&limit=1&appid=" + appid + "";
fetch(coordinatelink)
.then(response => response.json())
.then(data => {
// const coords = [{lat : data[0].lat ,
// lon : data[0].lon
// }];
let lat = data[0].lat;
let lon = data[0].lon;
const link = "https://api.openweathermap.org/data/2.5/onecall?lat=" + lat + "&lon=" + lon + "&appid=" + appid + "&units=metric";
return fetch(link);


})
.then(responce => responce.json())
.then(data => {

const sunrise = data.current.sunrise;
var sunriseDate = new Date(sunrise * 1000);
var sunriseHours = sunriseDate.getHours();
var sunriseMinutes = "0" + sunriseDate.getMinutes();
var sunriseSeconds = "0" + sunriseDate.getSeconds();
var sunriseFormattedTime = sunriseHours + ':' + sunriseMinutes.substr(-2) + ':' + sunriseSeconds.substr(-2);
const sunset = data.current.sunset;
var sunsetDate = new Date(sunset * 1000);
var sunsetHours = sunsetDate.getHours();
var sunsetMinutes = "0" + sunsetDate.getMinutes();
var sunsetSeconds = "0" + sunsetDate.getSeconds();
var sunsetFormattedTime = sunsetHours + ':' + sunsetMinutes.substr(-2) + ':' + sunsetSeconds.substr(-2);
// dataset = JSON.stringify(data["data"]);
dataset.push(JSON.stringify(data));

// res.redirect("http://localhost:3000/"+"cityname+");4

// res.redirect("http://localhost:3000");
}).catch(() => {
msg.textContent = "Please search for a valid city 😩";
});


});

app.get("/searchloc",function(req,res){
//use ejs to embed data and refer to onenote to for editing html


})

app.post("/searchloc", function(req,res){
cityname = req.body.city;
// let iconurl = "http://openweathermap.org/img/wn/"+ dataset.current.weather[0].icon+"@2x.png"
console.log(dataset);
res.render("searchloc",{cityname:cityname});
console.log(dataset);
// icon:iconurl
})




app.listen(process.env.PORT || 3000, function () {
console.log("server created");
})

您可以使用会话变量之类的东西来实现这一点。基于Node的HTTP服务器中的全局是服务器的全局,而不是请求的全局。你会让会话相互覆盖。同样,你也可以使用"声明数据集变量。Let和const具有块作用域,而var具有全局作用域。

最新更新