将我通过 node.js 请求 (https.get) 获得的变量传输到另一个 js 文件
Transferring variables that I got by node.js request (https.get) to another js file
这将是我第一次 post 在这里,所以我可能会含糊其词。
我试图通过 node.js 请求获取数据,然后将它们传递给另一个 js 文件,以便适当的 html 文件可以使用它们。
此应用程序的文件夹如下所示:
-App
-node_modules
-public
-css
-styles.css
-js
-currentWeather.js
-app.js
-currentWeather.html
-index.html
-package.json e.t.c
我在 app.js 中写道:
const express = require("express");
const https = require("https");
const bodyParser = require("body-parser");
const app = express();
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended:true}));
app.get("/",(req,res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/", (req,res) =>{
const city = req.body.city;
const url = .....
https.get(url, (response) => {
response.on("data", (data) => {
const weatherData = JSON.parse(data);
// and here somehow i want to export variable city and weatherData and send them to this currentWeather.js in public folder because i want to do DOM manipulation and some styling (currentWeather.html) with the data i got.
// res.sendFile(__dirname + "/currentWeather.html");
})
})
})
app.listen(3000, () => {console.log("Server is running on port 3000.");});
以及如何将它们放入此文件中? - currentWeather.js
您需要使用 promises 来等待回调完成。例如:
const https = require('https');
let result = await new Promise(resolve =>
require('https').get('https://www.example.com',res => res.on('data',resolve))
);
console.log(result.toString());
只需确保它在 async
函数内:
(async()=>{
// Do stuff
})()
这将是我第一次 post 在这里,所以我可能会含糊其词。 我试图通过 node.js 请求获取数据,然后将它们传递给另一个 js 文件,以便适当的 html 文件可以使用它们。 此应用程序的文件夹如下所示:
-App
-node_modules
-public
-css
-styles.css
-js
-currentWeather.js
-app.js
-currentWeather.html
-index.html
-package.json e.t.c
我在 app.js 中写道:
const express = require("express");
const https = require("https");
const bodyParser = require("body-parser");
const app = express();
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended:true}));
app.get("/",(req,res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/", (req,res) =>{
const city = req.body.city;
const url = .....
https.get(url, (response) => {
response.on("data", (data) => {
const weatherData = JSON.parse(data);
// and here somehow i want to export variable city and weatherData and send them to this currentWeather.js in public folder because i want to do DOM manipulation and some styling (currentWeather.html) with the data i got.
// res.sendFile(__dirname + "/currentWeather.html");
})
})
})
app.listen(3000, () => {console.log("Server is running on port 3000.");});
以及如何将它们放入此文件中? - currentWeather.js
您需要使用 promises 来等待回调完成。例如:
const https = require('https');
let result = await new Promise(resolve =>
require('https').get('https://www.example.com',res => res.on('data',resolve))
);
console.log(result.toString());
只需确保它在 async
函数内:
(async()=>{
// Do stuff
})()