Express.js项目POST /add路由无法正常工作求助
修复Express POST /add路由的500错误
从错误截图来看,你的POST /add路由返回了500内部服务器错误,核心问题是代码缺少错误处理逻辑,且未覆盖关键边界情况,导致请求失败。以下是具体修复方案:
关键问题分析
- 异步数据库操作未捕获异常,一旦查询出错会直接抛出未处理的Promise rejection
- 未处理「输入国家不存在」「重复插入已访问国家」等边界场景
- 数据库连接未做错误监听,连接失败时无法及时排查问题
修复后的完整代码
import express from "express"; import bodyParser from "body-parser"; import pg from "pg"; const app = express(); const port = 3000; const db = new pg.Client({ user: "postgres", host: "localhost", database: "world", password: "12345678", port: 5432, }); // 处理数据库连接错误 db.connect() .then(() => console.log("数据库连接成功")) .catch(err => console.error("数据库连接失败:", err)); db.on("error", (err) => { console.error("数据库连接意外断开:", err); }); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static("public")); async function checkVisisted() { try { const result = await db.query("SELECT country_code FROM visited_countries"); return result.rows.map(row => row.country_code); } catch (err) { console.error("查询已访问国家失败:", err); return []; } } // GET home page app.get("/", async (req, res) => { try { const countries = await checkVisisted(); res.render("index.ejs", { countries: countries, total: countries.length, error: req.query.error // 传递错误提示给页面 }); } catch (err) { console.error("渲染首页失败:", err); res.status(500).send("服务器内部错误"); } }); // INSERT new country app.post("/add", async (req, res) => { try { const input = req.body["country"]?.trim(); if (!input) { return res.redirect("/?error=请输入有效的国家名称"); } const result = await db.query( "SELECT country_code FROM countries WHERE country_name = $1", [input] ); if (result.rows.length === 0) { return res.redirect("/?error=未找到该国家,请检查输入"); } const countryCode = result.rows[0].country_code; // 提前检查是否已存在,避免重复插入 const existsCheck = await db.query( "SELECT 1 FROM visited_countries WHERE country_code = $1", [countryCode] ); if (existsCheck.rows.length > 0) { return res.redirect("/?error=该国家已在已访问列表中"); } await db.query( "INSERT INTO visited_countries (country_code) VALUES ($1)", [countryCode] ); res.redirect("/"); } catch (err) { console.error("添加国家失败:", err); // 捕获PostgreSQL唯一约束冲突错误(代码23505) if (err.code === "23505") { return res.redirect("/?error=该国家已在已访问列表中"); } res.redirect("/?error=添加国家时发生错误,请稍后重试"); } }); app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });
额外页面提示优化
在你的index.ejs中添加错误提示渲染逻辑,让用户能看到反馈:
<% if (error) { %> <div style="color: #dc2626; padding: 8px; background: #fef2f2; border-radius: 4px; margin-bottom: 16px;"> <%= error %> </div> <% } %>
内容的提问来源于stack exchange,提问作者Hashibul Hasan
相关产品推荐
相关产品推荐

