基于Node.js的API授权Web应用报错:找不到模块'js'求助
解决:"failed to make request Cannot find module 'js'" 错误
问题根源
你的POST路由中错误调用了res.render("index.js"),改为res.render("index.ejs")即可解决问题。
原因解释
Express的res.render()方法用于渲染模板文件,你的项目使用EJS作为模板引擎,必须指定.ejs后缀的模板文件。当传入index.js时,Express会尝试加载名为js的模板引擎模块,而该模块不存在,因此触发了"Cannot find module '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"); const result = response.data; 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 { const type = req.body.type; const participants = req.body.participants; const response = await axios.get(`https://bored-api.appbrewery.com/filter?type=${type}&participants=${participants}`); const result = response.data; // 修正模板文件后缀 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 match your criteria" }); } }); app.listen(port, () => { console.log(`Server running on port: ${ port }`); });
内容的提问来源于stack exchange,提问作者senpxi
相关产品推荐
相关产品推荐

