我是 Next.js 的新手,我正在为 API 路由而苦苦挣扎,或者确切地说,如何从这些路由中获取数据。我已经在 /api/weather.js 中编写了我的无服务器函数
export default async function handler(req, res) {
const city = req.query.city;
const getWeatherData = await fetch(
`https://api.weatherapi.com/v1/search.json?key=${process.env.WEATHER_API_KEY}&q=${city}&days=5&aqi=no&alerts=no`
);
const data = await getWeatherData.json();
res.status(200).json(data)
console.log(city)
}
城市未定义,因为我希望通过组件 SearchBar.js 中的输入字段搜索城市。现在 http://localhost:3000/api/cities 只返回一个空数组,当然,因为我需要一个城市名称来获取城市。但是城市名称应该来自 SearchBar.js。然而我并没有走到那里。我有一个查询,但这与我的 API 没有任何关联。
export const SearchBar = () => {
const [query, setQuery] = useState('')
const onChange = (e) => {
const {value} = e.target;
setQuery(value)
let matchingCities = []
if(value.length > 3) {
const test = fetch('/api/cities', {
method: 'GET'
}).then((response) => response.json())
console.log(test)
//test returns a promise pending
}
}
return(
<div className="sm:col-span-2">
<label htmlFor="email" className="block text-sm font-medium text-gray-700">
Search city
</label>
<div className="mt-1">
<input
onChange={onChange}
id="city"
name="city"
type="text"
value={query}
autoComplete="city"
className="py-3 px-4 block w-full shadow-sm focus:ring-blue-500 focus:border-blue-500 border-gray-300 rounded-md"
/>
</div>
</div>
)
}
我知道这可能太复杂了,但也许有人至少可以描述必要的步骤,将这些步骤连接起来,让这个查询在我输入的城市中工作。
一般来说,步骤是:
需要解决的几件事:
/api/weather.js
,因此在 SearchBar 中您应该调用/api/weather
,而不是/api/cities
city
参数,因此您需要将输入中的值传递给它:/api/weather?city=${value}
await
而不是.then
,使它更容易阅读(但这是可选的)请参阅此处的工作示例(检查控制台以获取输出):https : //codesandbox.io/s/next-js-api-with-lewagon-autocomplete-xrb3l?file=/components/SearchBar.jsx
我使用 LeWagon 的 API 而不是天气服务,它不需要密钥 :)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句