未指定默认引擎且未提供扩展名,终端会抛出错误

问题描述 投票:0回答:1

我正在尝试在nodejs中执行后端程序,并且正在使用mongodb。我正在创建一个表单,其中只有2个输入字段,其中有密码和名称。我没有使用任何 hbs 或 ejs,也没有默认引擎,但我的 VS Code 终端显示

"No default engine was specified and no extension was provided.
    at new View (C:\Users\LENOVO\Desktop\adin\backend\node_modules\express\lib\view.js:61:11)
    at Function.render (C:\Users\LENOVO\Desktop\adin\backend\node_modules\express\lib\application.js:587:12)
    at ServerResponse.render (C:\Users\LENOVO\Desktop\adin\backend\node_modules\express\lib\response.js:1039:7)
    at C:\Users\LENOVO\Desktop\adin\backend\src\app.js:46:25
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)"


app.js

const static_path =path.join(__dirname,"../public");

app.use(express.json());
app.use(express.urlencoded({ extended: false })); 
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(static_path));

app.get("/",(req,res)=>{
    res.render("index");
});

app.get("/index",(req,res)=>{
    res.render("index");
})


//create a new user in database
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).render("index");
        
    }catch(error){
        res.status(400).send(error);
        console.log(error);
    }
})


app.listen(port, ()=>{
    console.log(`server is running at port no ${port}`);
})
javascript html css node.js mongodb
1个回答
0
投票

res.render()
负责渲染从模板生成的视图,并需要您设置模板引擎

由于您要发送

.html
文件,您需要使用
res.sendFile()
方法

所以你的渲染逻辑就变成了

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

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

您可以查看

expressJS
有关它的文档这里

© www.soinside.com 2019 - 2024. All rights reserved.