求助:基于Bored API的活动查询网站触发404请求失败错误
问题排查与解决方案
错误原因
- API请求URL格式错误:POST请求中axios调用的URL模板字符串包含换行和多余空格,导致实际请求的URL带有无效空格,触发服务器404错误。
- 空参数未处理:当用户选择「Random type」或「Any number of people」时,
type或participants会是空字符串,直接拼入URL会导致API参数无效,可能返回空数组或错误。 - 空数组未处理:即使API成功返回空数组(无匹配活动),代码仍尝试从空数组中随机取元素,会触发新错误并走到catch分支显示错误信息。
解决方案
1. 修正API URL格式
删除URL模板字符串中的换行和多余空格,确保地址连续有效。
2. 动态拼接有效参数
仅将有值的参数拼入请求URL,避免空参数干扰API逻辑。
3. 处理空数组返回情况
获取API响应后先判断数组是否为空,为空则直接渲染错误信息,再随机选取活动。
修改后的Index.js代码
import express from "express"; import bodyParser from "body-parser"; import axios from "axios"; const app = express(); const port = 3000; app.use(express.static("public")); app.use(bodyParser.urlencoded({ extended: true })); app.get("/", async (req, res) => { try { const response = await axios.get("https://bored-api.appbrewery.com/random"); let result = response.data; console.log(result); res.render("index.ejs", { data: result }); } catch (error) { console.error("Failed to make request:", error.message); res.render("index.ejs", { error: error.message }); } }); app.post("/", async (req, res) => { try { console.log(req.body); const type = req.body.type; const participants = req.body.participants; // 动态构建请求参数 let params = []; if (type) params.push(`type=${type}`); if (participants) params.push(`participants=${participants}`); const queryString = params.join("&"); // 无参数时直接请求随机活动接口 const url = queryString ? `https://bored-api.appbrewery.com/filter?${queryString}` : `https://bored-api.appbrewery.com/random`; const response = await axios.get(url); const result = response.data; // 处理空数组情况 if (result.length === 0) { res.render("index.ejs", { error: "No activities that match your criteria." }); return; } res.render("index.ejs", { data: result[Math.floor(Math.random() * result.length)], }); } catch (error) { console.error("Failed to make request:", error.message); res.render("index.ejs", { error: "No activities that match your criteria." }); } }); app.listen(port, () => { console.log(`Server running on port: ${port}`); });
可选优化
删除index.ejs中card-participants里的无用标签:
<span class="card-participants"> participants: <%= data.participants %> </span>
内容的提问来源于stack exchange,提问作者TylerDurden
相关产品推荐
相关产品推荐

