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

如何在嵌套Post请求的If语句中传递4个键值对到success.ejs页面

实现方案

1 调整后端代码逻辑

你现有代码的核心问题是请求天气接口成功后直接写死HTML返回,没有调用EJS模板渲染,且多余的POST /success路由为无效的死循环重定向,按以下方式修改即可:
首先确保你已经在代码顶部配置了EJS模板引擎和静态资源解析规则:

const express = require('express');
const https = require('https');
const app = express();

// 基础配置,放在所有路由之前
app.set('view engine', 'ejs'); // 启用ejs模板引擎
app.use(express.static('public')); // 配置静态资源目录,CSS等文件放在该目录下
app.use(express.urlencoded({extended: true})); // 解析POST请求的body参数

再修改原有POST路由逻辑:

app.post("/", function(req, res){
  const query = req.body.cityName;
  const unit = "metric";
  const apiKey = "********";
  const url = "https://api.openweathermap.org/data/2.5/weather?appid=" + 
  apiKey + "&q=" + query + "&units=" + unit;

  https.get(url, function(response){
    console.log(response.statusCode);

    if (response.statusCode === 200) {
      response.on("data", function(data){
        const weatherData =  JSON.parse(data);
        const temp = weatherData.main.temp;
        const weatherDescription = weatherData.weather[0].description;
        const icon = weatherData.weather[0].icon;
        const imageURL = "http://openweathermap.org/img/wn/" + icon + "@2x.png";
        // 删掉原有res.write代码,直接渲染ejs模板并传递参数
        res.render('success', {
          weatherDescription,
          query,
          temp,
          imageURL
        });
      });
    } else {
      res.sendFile(__dirname + "/failure.html");
    }
  });
});

// 删掉无效的POST /success路由
app.post("/failure", function(req, res) {
  res.redirect("/");
});

app.listen(3000);

2 配置success.ejs样式

首先在项目根目录创建public/css文件夹,新建success.css文件编写样式,示例如下:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body {
  font-family: "微软雅黑", sans-serif;
  background-color: #e3f2fd;
  padding: 80px 20px;
}
.weather-card {
  max-width: 500px;
  margin: 0 auto;
  background: #fff;
  padding: 40px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.08);
  text-align: center;
}
.city-name {
  font-size: 36px;
  color: #1976d2;
  margin-bottom: 16px;
}
.weather-desc {
  font-size: 22px;
  color: #424242;
  text-transform: capitalize;
  margin-bottom: 24px;
}
.temp-value {
  font-size: 64px;
  font-weight: bold;
  color: #212121;
  margin-bottom: 16px;
}
.weather-icon {
  width: 120px;
  height: 120px;
}

再修改success.ejs文件,引入样式并调整结构:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>天气查询结果</title>
  <!-- 引入刚才编写的CSS文件 -->
  <link rel="stylesheet" href="/css/success.css">
</head>
<body>
  <div class="weather-card">
    <h1 class="city-name"><%= query %></h1>
    <p class="weather-desc"><%= weatherDescription %></p>
    <p class="temp-value"><%= temp %> °C</p>
    <img src="<%= imageURL %>" alt="天气图标" class="weather-icon">
  </div>
</body>
</html>

注意事项

如果你的EJS文件没有存放在项目根目录默认的views文件夹下,需要在基础配置中额外指定模板文件路径:app.set('views', path.join(__dirname, '你的EJS文件存放目录路径'))。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:36:06