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

解决Express中Axios调用weatherstack API返回温度的POST请求错误

解决Weatherstack API + Express POST请求的错误问题

你的代码存在几个关键问题,直接导致了运行错误,以下是具体分析和修复方案:

核心错误点

  1. Axios响应处理错误:你写的const{response} = await axios(...)完全错误,axios发起请求后返回的响应对象中,接口返回的实际数据在data属性里,正确做法是直接接收响应对象,或者解构data字段。
  2. 缺少错误处理机制:异步API请求没有任何异常捕获,一旦出现网络问题、城市名称无效或API密钥错误,服务器会直接崩溃。
  3. 未处理用户无效输入:没有校验用户提交的城市名称,空输入会触发无效的API请求。

修复后的完整代码

app.js

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const axios = require('axios');

const access_key = '...'; // 替换为你的Weatherstack有效API密钥

app.use(bodyParser.urlencoded({ extended: false }));

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

app.post('/', async function (req, res) {
    // 校验用户输入,避免空提交
    const cityName = req.body.cityName?.trim();
    if (!cityName) {
        return res.send(`<p>请输入有效的城市名称!</p><a href="/">返回</a>`);
    }

    try {
        // 正确调用API,用encodeURIComponent处理城市名特殊字符
        const apiResponse = await axios.get(`http://api.weatherstack.com/current?access_key=${access_key}&query=${encodeURIComponent(cityName)}`);
        const weatherData = apiResponse.data;

        // 处理API返回的错误(比如城市不存在)
        if (weatherData.error) {
            return res.send(`<p>错误提示:${weatherData.error.info}</p><a href="/">返回</a>`);
        }

        // 返回格式化的温度结果
        res.send(`
            <p>当前${weatherData.location.name}的温度是 ${weatherData.current.temperature} ℃</p>
            <a href="/">返回重新查询</a>
        `);
    } catch (error) {
        // 捕获所有异常,避免服务器崩溃
        console.error('API请求失败:', error.message);
        res.send(`<p>请求失败,请检查API密钥或稍后重试!</p><a href="/">返回</a>`);
    }
});

app.listen(4000, () => {
    console.log("Server running on localhost:4000");
});

关键优化说明

  • 使用encodeURIComponent()处理城市名称:避免城市名包含空格、特殊字符时导致URL格式错误
  • 增加输入校验:拦截空提交,提升用户体验
  • 处理API内置错误:Weatherstack API在请求失败时会返回error字段,直接展示给用户更友好
  • 全局异常捕获:任何异步错误都会被捕获,保证服务器持续运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:31:14