Express框架中404错误跳转自定义失败页面的问题求助
问题根因
现有代码存在3个核心问题导致404时崩溃:
- 404状态判断后调用
res.sendFile返回失败页,但未终止后续代码执行,会继续尝试解析接口返回内容、发送定义查询结果,单次请求多次调用响应方法直接触发报错 - 直接在
response.on("data")事件中解析JSON,未考虑HTTP响应分块传输的场景,很容易出现JSON结构截断解析失败 - 未对接口返回结构做容错校验,即使状态码正常,结构不符合预期时也会崩溃
修复后的服务端代码
const express = require("express"); const bodyParser = require("body-parser"); const https = require("https"); const app = express(); app.use(bodyParser.urlencoded({extended: true})); app.get("/", function(req, res) { res.sendFile(__dirname + "/search.html"); }) app.post("/", function(req, res) { const word = req.body.word; const code = req.body.code; const url = "https://api.dictionaryapi.dev/api/v2/entries/" + code + "/" + word; https.get(url, function(response) { // 先判断状态码,异常状态直接返回失败页,终止后续逻辑 if(response.statusCode >= 400){ return res.sendFile(__dirname + "/failure.html"); } // 拼接所有响应数据后再处理 let rawData = ''; response.on('data', (chunk) => { rawData += chunk; }); response.on('end', () => { try { const meaning = JSON.parse(rawData); // 增加结构容错判断 if(meaning && meaning.length && meaning[0].meanings?.length && meaning[0].meanings[0].definitions?.length){ const definition = meaning[0].meanings[0].definitions[0].definition; res.send("<h1>" + definition + "</h1>"); } else { res.sendFile(__dirname + "/failure.html"); } } catch (e) { // JSON解析失败返回失败页 res.sendFile(__dirname + "/failure.html"); } }); }).on('error', (e) => { // 请求本身报错也返回失败页 res.sendFile(__dirname + "/failure.html"); }) }) app.post("/failure", function(req, res) { res.redirect("/"); }) // 全局404路由,处理不存在的路径访问 app.use(function(req, res) { res.sendFile(__dirname + "/failure.html"); }) app.listen(process.env.PORT || 3000, function() { console.log("Server running properly"); })
failure.html示例代码(匹配预期效果)
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>查询失败</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; font-family: sans-serif; } .container { width: 100vw; height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; background-color: #f5f5f5; } h1 { font-size: 48px; color: #333; margin-bottom: 20px; } p { font-size: 18px; color: #666; margin-bottom: 30px; } button { padding: 12px 24px; font-size: 16px; background-color: #2196F3; color: #fff; border: none; border-radius: 4px; cursor: pointer; } button:hover { background-color: #1976D2; } </style> </head> <body> <div class="container"> <h1>Oops!</h1> <p>未查询到该单词的释义,请确认输入内容是否正确</p> <form action="/failure" method="POST"> <button type="submit">返回首页重新查询</button> </form> </div> </body> </html>
内容的提问来源于stack exchange,提问作者msbtech
相关产品推荐
相关产品推荐

