如何发送数据从api接收到我设计的html页面



基本上我是一个初学者在web开发我设计了一个基本的天气报告网站使用Openweather api我从api收到的数据,但主要问题是我不能从api传递数据到我的html页面,我甚至使用DOM发送信息,但它没有工作。

'''
const express = require("express");
const bodyParser = require("body-parser");
const http = require("http");
var app = express();
app.use(bodyParser.urlencoded({extended:true}));

app.use(express.static("./public"));
app.get("/",(request,response)=>{
response.sendFile('/Users/vivek/Desktop/web-development/weather- 
app/public');
});
app.get("/weatherdata",(request,response)=>{
response.sendfile('/Users/vivek/Desktop/web-development/weather- 
app/public/weatherData.html');
})
app.post("/weatherdata",(req,res)=>{
res.sendfile('./public/weatherData.html');
var cityname = req.body.cityName;
var apiid = "b75642448cbd207923a63b89cf48768d";
var url = "http://api.openweathermap.org/data/2.5/weather? 
q="+cityname+"&appid="+apiid;
http.get(url,(res=>{
console.log(res.statusCode)
res.on("data",(data)=>{
data = JSON.parse(data);
temp = data.main.temp;
console.log(temp);
document.querySelector(".main-degree").innerHTML=temp;
})
}))
})
app.listen(7000,()=>{
console.log("sever is running on port 7000");
});

在注释上展开,您可以使用像ejs这样的模板引擎。顾名思义,它是一个使用Openweather API的响应来呈现的模板。

基本过程:

  1. 当用户打开站点
  2. 控制器将调用API并获得响应
  3. 用响应
  4. 呈现. js页面

这是EJS的入门页:https://ejs.co/#install

另一个建议:

  • 为所有文件使用相对路径。这样做的好处是,即使有人移动了项目,也不会有什么问题。

最新更新