You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将React输入框值设为Express中OpenWeatherAPI的查询参数

实现React搜索值传递给Express后端并动态调用OpenWeatherAPI

前端React实现

先创建一个带搜索框的组件,通过状态管理输入值,提交时将值发送到后端接口:

// React搜索组件示例
import { useState } from 'react';

function WeatherSearch() {
  const [city, setCity] = useState('');
  const [weatherData, setWeatherData] = useState(null);
  const [errorMsg, setErrorMsg] = useState('');

  const handleSearchSubmit = async (e) => {
    e.preventDefault();
    if (!city.trim()) {
      setErrorMsg('请输入有效的城市名称');
      return;
    }

    try {
      // 发送GET请求到后端接口,携带城市参数
      const res = await fetch(`/api/weather?city=${encodeURIComponent(city)}`);
      if (!res.ok) throw new Error('天气数据获取失败');
      const data = await res.json();
      setWeatherData(data);
      setErrorMsg('');
    } catch (err) {
      setErrorMsg(err.message);
      setWeatherData(null);
    }
  };

  return (
    <div className="weather-search">
      <form onSubmit={handleSearchSubmit}>
        <input
          type="text"
          value={city}
          onChange={(e) => setCity(e.target.value)}
          placeholder="输入城市名搜索天气"
        />
        <button type="submit">查询</button>
      </form>
      
      {errorMsg && <p className="error">{errorMsg}</p>}
      
      {weatherData && (
        <div className="weather-result">
          <h3>{weatherData.name}</h3>
          <p>当前温度: {weatherData.main.temp}°C</p>
          <p>天气状况: {weatherData.weather[0].description}</p>
        </div>
      )}
    </div>
  );
}

export default WeatherSearch;

后端Express实现

在server.js中编写API路由,接收前端传递的城市参数,动态拼接OpenWeatherAPI的查询参数并返回结果:

// server.js示例
const express = require('express');
const axios = require('axios');
const app = express();
const PORT = process.env.PORT || 3001;

// 替换为你的OpenWeatherAPI密钥
const OPENWEATHER_API_KEY = '你的API密钥';
const OPENWEATHER_BASE_URL = 'https://api.openweathermap.org/data/2.5/weather';

// 解析请求体(若使用POST请求则需要)
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 天气查询API路由
app.get('/api/weather', async (req, res) => {
  try {
    const { city } = req.query;
    if (!city) {
      return res.status(400).json({ error: '缺少城市参数' });
    }

    // 调用OpenWeatherAPI,动态设置q参数
    const apiRes = await axios.get(OPENWEATHER_BASE_URL, {
      params: {
        q: city,
        appid: OPENWEATHER_API_KEY,
        units: 'metric' // 设置温度单位为摄氏度
      }
    });

    // 将API返回的天气数据转发给前端
    res.json(apiRes.data);
  } catch (err) {
    console.error('OpenWeatherAPI调用错误:', err);
    // 处理API返回的错误信息
    const errMsg = err.response?.data?.message || '获取天气数据失败';
    res.status(err.response?.status || 500).json({ error: errMsg });
  }
});

// 托管React构建后的静态文件(若前后端同域部署)
app.use(express.static('client/build'));

app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});

关键注意事项

  • 务必替换代码中的OPENWEATHER_API_KEY为你自己的OpenWeather API密钥,否则接口调用会失败
  • 前端使用encodeURIComponent处理城市名称,避免特殊字符导致URL解析错误
  • 可根据需求切换请求方式(GET/POST),若用POST,前端需将参数放在请求体中,后端从req.body获取
  • 增加了基础错误处理,涵盖输入为空、API调用失败等场景

内容的提问来源于stack exchange,提问作者Arsalan Najm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 17:10:32