如何将变量从服务器js文件传递到另一个

时间:2020-04-02 21:41:45

标签: javascript html node.js api express

我正在构建一个简单的天气网页。我使用节点js服务器文件从开放式天气api获取天气信息

问题是,一旦我获得了诸如温度之类的天气信息,然后将其设置在变量上,便无法将其传递给其他javascript文件,以便能够在新的html文件中显示。我想将weatherState变量传递到另一个js文件,以便将其包含在我的weather.html中。这是代码

app.post("/", function(req, res) {
    const url = "https://api.openweathermap.org/data/2.5/weather?q=london&appid=****&units=metric

  https.get(url, function(response) {
    response.on("data", function(data) {
      const weatherData = JSON.parse(data);
      var weatherState = "The temperature in london  is: " + weatherData.main.temp + " degrees
      res.sendFile(__dirname + "/weather.html");

    });
  });
});

我尝试做module.export事情,但是浏览器不允许我使用node从其他文件中进行请求。

我只是想以某种方式在我的weather.html文件中显示weatherState变量

1 个答案:

答案 0 :(得分:1)

尝试使用带有节点js的Ejs模板。在这里找到链接 https://scotch.io/tutorials/use-ejs-to-template-your-node-application