node.js - 将数据从反应应用程序移动到节点服务器
问题描述
我已经使用 react 创建了一个天气应用程序。我正在使用 openweathermap.org 来获取数据。用户输入邮政编码。该邮政编码用于获取纬度/经度,然后获取天气预报。我想在节点中执行我的 api 获取,而不是做出反应,所以如果有人使用他们浏览器的检查工具,我的 API 密钥会被隐藏。用户输入邮政编码后,如何将该数据拉入节点,以在服务器端执行提取,而不是做出反应?以及如何将结果移回以做出反应,以显示结果。谢谢您的帮助。
天气.js
import React, {useState, useEffect} from "react"
import Button from "./Button"
const API_KEY = process.env.REACT_APP_API_KEY
function Weather() {
const [loading, setLoading] = useState(false)
const [maxTemp0, setMaxTemp0] = useState([])
const [lat, setLat] = useState("34")
const [long, setLong] = useState("-118")
const [zip, setZip] = useState("90210")
useEffect(()=>{
fetch("https://api.openweathermap.org/geo/1.0/zip?zip="+ zip +",US&appid="+ API_KEY +"")
.then(res => res.json())
.then((result) => {
// Set new lat/long from zip fetch
setLat(result.lat)
setLong(result.lon)
console.log(lat)
console.log(long)
console.log(zip)
console.log(result)
})
}, [zip, lat, long])
useEffect(()=>{
fetch("https://api.openweathermap.org/data/2.5/onecall?lat="+ lat +"&lon="+ long +"&units=imperial&exclude=current,minutely,hourly,alerts&appid="+ API_KEY +"")
.then(res => res.json())
.then((data) => {
// Set weather data from weather fetch
setMaxTemp0(data.daily[0].temp.max)
})
}, [lat, long])
if(loading === true){
return <div>Loading...</div>
} else return(
<div>
<Button zip={setZip} /> <br />
High: {Math.round(maxTemp0)}
</div>
)
}
export default Weather
按钮.js
import React, {useState} from "react"
function Button(props) {
const [zip, setZip] = useState([])
const handleSubmit = (event) => {
console.log(zip)
props.zip(`${zip}`)
event.preventDefault();
}
return(
<div>
<input placeholder="Zip Code" type="number" min="0" max="99999" value={zip} onChange={(e) => setZip(e.target.value)} />
<button onClick={handleSubmit}>Submit</button>
</div>
)
}
export default Button
服务器.js
const express = require("express")
const app = express()
const path = require("path")
const port = process.env.PORT || 5000
app.use("/weather",express.static(path.join("weather/build")))
app.use("/",express.static(path.join("portfolio")))
app.listen(port, () => console.log("Working"))
解决方案
推荐阅读
- spring-integration - 使用 jdbcPollingChannelAdapter 执行多个查询
- java - 在一种方法中返回基类的各种实现
- javascript - 用javascript读取条形码
- javascript - 我可以同步运行 ytdl getInfo() 吗?
- amazon-web-services - ECS服务“稳定”状态查询
- postgresql - 无法从 postgres 获取结果
- python - 在标题下查找文本的最佳方法是什么
- javascript - 如果函数和参数都被“包装”,如何使用提升
- javascript - 内联块和自动换行 - 自动换行后元素大小是否可以与确切的文本区域匹配?
- postgresql - 将 Metricbeats Postgresql 模块日志记录限制到单个数据库