html - 无法获取 /index.html。在学习有关 Node.js 和 MongoDB 的教程时
问题描述
我正在按照从这里创建注册表单的指南。按照它的步骤尝试连接时会出现错误http://127.0.0.1:3000/
无法获取 /index.html
我MongoDB
从C:\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");
解决方案
所以你的问题是你正在使用render
你的观点。但是,您尚未指定渲染引擎(ejs、pug 等...)。
话虽如此,HTML 文件不需要渲染引擎。您可以像这样简单地为他们服务:
app.get('/', (req, res) => {
res.sendFile('index.html', {
root: './'
}
})
推荐阅读
- java - 解决了!- Spring boot:获取 415 不支持的媒体类型
- python - 使用 ULMFiT 和 Python 中的 fastai 库进行文本分类 (NLP)
- gitlab - GitLab: stores large objects (LFS) outside of lfs_storage_path
- java - Why doesn't SpyPostProcessor implement getEarlyBeanReference() like AbstractAutoProxyCreator,it may cause circular reference Exception
- python - 禁用 python 问候/版本信息
- java - JDK version 1.8 in the system but JDK 11 on VScode
- node.js - Connection Not established in Mocha to MongoDB Atlas
- android - Centrally place menu items in bottom navigation view without text
- python - Python:cx_Oracle 不喜欢我输入日期的方式
- flutter - 从图像加载调色板后极度滞后