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

Node.js+MongoDB后端项目报错:No default engine was specified and no extension was provided

错误原因分析

错误No default engine was specified and no extension was provided的核心原因是你调用了res.render()方法,但既未配置Express模板引擎,也未给渲染文件指定扩展名。res.render()是专门用于渲染模板文件(如EJS、HBS等)的API,并非返回静态HTML的方法。

解决方案

结合你使用静态HTML表单的需求,提供两种可行方案:

方案一:改用res.sendFile()返回静态HTML

你已通过express.static托管了public目录,直接用res.sendFile替代res.render即可:

修改路由代码如下:

app.get("/",(req,res)=>{
    res.sendFile(path.join(static_path, "index.html"));
});

app.get("/index",(req,res)=>{
    res.sendFile(path.join(static_path, "index.html"));
})

app.post("/index",async (req,res)=>{
    try{
        const indexSchema=new Index({
            name: req.body.name,
            password: req.body.password
        });

        const indexed=await indexSchema.save();
        res.status(201).sendFile(path.join(static_path, "index.html"));
        
    }catch(error){
        res.status(400).send(error);
        console.log(error);
    }
})

注意:需确保public目录下存在index.html文件,否则会返回404。

方案二:配置模板引擎(若需动态内容)

如果后续需要渲染动态页面,可选择模板引擎(如EJS),步骤如下:

  1. 安装EJS:
npm install ejs
  1. 在app.js中配置模板引擎:
// 设置视图文件存放目录(示例为项目根目录下的views文件夹)
app.set('views', path.join(__dirname, '../views'));
// 设置默认模板引擎为EJS
app.set('view engine', 'ejs');
  1. 将public目录下的index.html移至views目录并改名为index.ejs,之后即可正常使用res.render("index")。
额外优化建议

你同时使用了express.urlencoded和bodyParser.urlencoded,二者功能重复。Express 4.16+已内置bodyParser的核心功能,建议保留以下配置即可:

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

内容的提问来源于stack exchange,提问作者Adin Shahab

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:52:36