【发布时间】:2021-03-29 23:39:24
【问题描述】:
我有一个快速后端,当从 React 表单发出 POST 请求时,它会向 OpenWeather API 发出 GET 请求。目前,问题在于后端 POST 路由我认为没有正确调用并且无法存储搜索词。在调试时,我从前端发出了一个获取请求,该请求有效,并且我还使用相同的路径放入了一个存储在 express 中的虚拟数组,该路径不起作用并且可以从前端和后端获取。
网络选项卡中没有显示 POST 请求,只有响应为 304 的 GET 请求,但在控制台中我收到“cod:”400”,消息:“错误查询”,我假设这是来自的错误消息OpenWeather API
反应代码
const WeatherContainer = () => {
let [searchTerm, setsearchTerm] = useState('')
let [currentWeather, setCurrentWeather] = useState({});
let [forecastedWeather, setForecastedWeather] = useState({});
let [loading, setLoading] = useState(false);
const handleInput = (e) => {
setsearchTerm(e.target.value);
}
const handleSearch = () => {
fetch('/search-weather')
.then(res => res.json())
.then(data => {
setCurrentWeather({data})
console.log(data)
})
};
return (
<>
<div className='search-bar'>
<form method="POST" action='/search-term'>
<input className='text_input' type='text' name='searchTerm' onChange={handleInput} placeholder='Enter city' />
<button className='search-button' onClick={handleSearch} type='submit' value='submit' name='button'>
<Icon icon={searchIcon} flip="horizontal" />
</button>
</form>
</div>
{}
<div className='weather_container'>
<CurrentWeatherComponent />
<ForecastContainer />
</div>
</>
)
};
快递代码
const express = require('express');
const PORT = 5000;
const fetch = require('node-fetch')
const app = express();
//const server = require('http').createServer(app);
const weatherApiKey = '****HIDDEN****';
const cors = require('cors');
app.use(express.static("client"));
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
let searchTerm;
// Post From Input, Route uses 'searchTerm' name attribute in input
app.post('/search-term', (req, res) => {
searchTerm = req.body.searchTerm;
});
// GET Current & Forecast Weather By Search Term
app.get('/search-weather', (req, res) => {
const currentUrl = `http://api.openweathermap.org/data/2.5/weather?q=${searchTerm}&units=imperial&appid=${weatherApiKey}`;
fetch(currentUrl)
.then(response => response.json())
.then(currentData => {
return res.json({currentData})
})
.catch(err => {
res.redirect('/error')
});
});
app.listen(PORT);
console.log(`Server is listening on ${PORT}`);
【问题讨论】:
标签: javascript node.js reactjs express