首页 > 解决方案 > 无法获取 /index.html。在学习有关 Node.js 和 MongoDB 的教程时

问题描述

我正在按照从这里创建注册表单的指南。按照它的步骤尝试连接时会出现错误http://127.0.0.1:3000/

无法获取 /index.html

MongoDBC:\Program Files\MongoDB\Server\4.4\bin

我对代码的唯一更改是

mongoose.connect('mongodb://localhost:27017/gfg', { useNewUrlParser: true, useUnifiedTopology: true }); 

自从启动应用程序时,它声明有已弃用的应用程序,但它什么也没做。

MongoDB 正确启动

mongod {"t":{"$date":"2020-09-28T20:39:11.740-04:00"},"s":"I",  "c":"NETWORK",  "id":23016,   "ctx":"listener","msg":"Waiting for connections","attr":{"port":27017,"ssl":"off"}}

和节点应用程序server listening at port 3000 connection succeeded,所以我不知道我在哪里搞砸了

我的目录看起来像这样

project root 
     ├── app.js
     ├── index.html
     └── package-lock.json
     ├── signup_success.html
     ├── style.css

Firefox 给了我一个404 GET error on inspection

这是 app.js

var express=require("express"); 
var bodyParser=require("body-parser"); 
  
const mongoose = require('mongoose'); 
mongoose.connect('mongodb://localhost:27017/gfg', { useNewUrlParser: true, useUnifiedTopology: true }); 
var db=mongoose.connection; 
db.on('error', console.log.bind(console, "connection error")); 
db.once('open', function(callback){ 
    console.log("connection succeeded"); 
}) 
  
var app=express() 
  
  
app.use(bodyParser.json()); 
app.use(express.static(__dirname + "/../public")); 
app.use(bodyParser.urlencoded({ 
    extended: true
})); 
  
app.post('/sign_up', function(req,res){ 
    var name = req.body.name; 
    var email =req.body.email; 
    var pass = req.body.password; 
    var phone =req.body.phone; 
  
    var data = { 
        "name": name, 
        "email":email, 
        "password":pass, 
        "phone":phone 
    } 
db.collection('details').insertOne(data,function(err, collection){ 
        if (err) throw err; 
        console.log("Record inserted Successfully"); 
              
    }); 
          
    return res.redirect('signup_success.html'); 
}) 
  
  
app.get('/', (req,res) => {   res.render('index.html');
    }).listen(3000) 
  
  
console.log("server listening at port 3000"); 

标签: htmlnode.jsmongodbexpressmongoose

解决方案


所以你的问题是你正在使用render你的观点。但是,您尚未指定渲染引擎(ejs、pug 等...)。

话虽如此,HTML 文件不需要渲染引擎。您可以像这样简单地为他们服务:

app.get('/', (req, res) => {
   res.sendFile('index.html', {
     root: './'
   }
})

推荐阅读