我正在使用OpenWeather API构建一个天气应用程序。 在Node中获取API,然后将数据传递给React前端,代码如下:
节点index.js
const express = require('express');
const cors = require('cors');
const app = express();
const axios = require('axios');
const dotenv = require('dotenv');
dotenv.config();
const url = `http://api.openweathermap.org/data/2.5/weather?q=london,uk&APPID=${process.env.REACT_APP_WEATHER_API_KEY}`;
app.use(cors());
app.get('/', (req, res) => {
res.send('go to /weather to see weather')
});
app.get('/weather', (req, res) => {
axios.get(url)
.then(response => {res.json(response.data)})
.catch(error => {
console.log(error);
});
})
let port = process.env.PORT || 4000;
app.listen(port, () => {
console.log(`App running on port ${port} `);
});
然后可以在http://localhost:4000/weather
中查看天气数据。 然后使用React来显示数据。 假设有一个简单的React组件来接受天气输入和更新状态:
反应weatherform.js
import React from 'react';
class WeatherForm extends React.Component {
constructor(props) {
super(props);
this.state = {
country: '',
city: ''
}
}
updateLocation(e) {
this.setState({
country: e.target.value,
city: e.target.value
});
}
render() {
return (
<form>
<div className="field">
<label className="label">Country</label>
<div className="control">
<input
className="input"
type="text"
placeholder="Type country name here"
onChange={e => this.updateLocation(e)} />
</div>
</div>
<div className="field">
<label className="label">City</label>
<div className="control">
<input
className="input"
type="text"
placeholder="Type city name here"
onChange={e => this.updateLocation(e)} />
</div>
</div>
<div className="field">
<div className="control">
<input
type='submit'
value='Search' />
</div>
</div>
</form>
)
}
}
export default WeatherForm
问题:如何将来自React app表单的国家/地区和城市用户输入传递到节点代码中该行url
变量中的国家/地区和城市?
const url = `http://api.openweathermap.org/data/2.5/weather?q=city,country&APPID=${process.env.REACT_APP_WEATHER_API_KEY}`
更新我已更新weatherform
组件,如下所示:
import React from 'react';
import Axios from 'axios';
class WeatherForm extends React.Component {
constructor(props) {
super(props);
this.state = {
country: '',
city: ''
}
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
const url = 'http://localhost:4000/weather';
const location = {
country: this.state.country,
city: this.state.city
}
Axios.post(url, location).then((res) => {
// what should I do here?
}).catch((e) => {
console.log(e);
})
}
updateLocation(e) {
this.setState({
country: e.target.value,
city: e.target.value
});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<p className="title">Weather</p>
<p className="subtitle">Check weather by city and country</p>
<div className="field">
<label className="label">Country</label>
<div className="control">
<input
className="input"
type="text"
placeholder="Type country name here"
onChange={e => this.updateLocation(e)} />
</div>
</div>
<div className="field">
<label className="label">City</label>
<div className="control">
<input
className="input"
type="text"
placeholder="Type city name here"
onChange={e => this.updateLocation(e)} />
</div>
</div>
<div className="field">
<div className="control">
<input
type='submit'
value='Search' />
</div>
</div>
</form>
)
}
}
export default WeatherForm
我得到错误:post http://localhost:4000/weather 404(未找到)
您希望使用http请求将数据发送到后端。 您可以使用本机window.fetch
API通过post请求发送数据,也可以使用第三方库(我建议使用axios)。
在react中发送form submit上的post请求的推荐方法是将字段数据存储在state中(在输入字段上使用onChange
属性,以便在输入值更改时更新状态),然后使用在单击submit按钮时激发的处理程序函数(对button元素使用onClick
属性)。
处理程序函数应该获取当前状态(表单输入字段数据),并将其作为主体传递到post请求中。
当您的express API收到请求时,它可以解析数据,然后将它自己的API请求作为url参数发送到openWeather API。
更新:
由于更新的问题正在更新。 您没有在express API中定义post路由。 因此它不会接受/weather路由的post请求。 您需要做的是编写一个接受post请求的处理程序:
app.post('/weather', (req, res, next) => {
let { country, city } = req.body.data;
// here you send a post request to the weather API url
// to retrieve the results, then send them back
// to your react app to display them
}