node.js - app.get 不能在主 index.html 上工作,但它可以在不存在的 html 页面上工作
问题描述
我是节点和快递的新手。
我正在关注本教程https://zellwk.com/blog/crud-express-mongodb/。
该app.get
函数在 index.html 页面上不起作用。它不会向终端控制台记录任何内容。奇怪的是,如果我更改"/"
为"/quotes"
(我没有 /quotes.html 页面),它会登录到终端。
加载页面还不够吗?我必须以某种方式调用该app.get()
函数吗?
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const MongoClient = require("mongodb").MongoClient;
PORT = process.env.PORT || 3000;
app.use(bodyParser.urlencoded({ extended: true }));
// Serve and index.html file that is found
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
// start server
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
const username = "hidden"
const password = "hidden"
const connectionString = `mongodb+srv://${username}:${password}@cluster0.7k2ww.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
MongoClient.connect(connectionString, { useUnifiedTopology: true })
.then((client) => {
console.log("Connected to Database");
const db = client.db("star-wars-quotes");
const quotesCollection = db.collection("quotes");
app.set("view engine", "ejs");
// app.use(/* ... */);
app.post("/quotes", (req, res) => {
quotesCollection
.insertOne(req.body)
.then((result) => {
res.redirect("/");
})
.catch((err) => console.log(err));
});
app.get("/", (req, res) => { // <-- Problem is here
db.collection("quotes")
.find()
.toArray()
.then((results) => {
console.log(results); // <-- Nothing happens here
})
.catch((err) => console.log(err));
});
app.listen(/* ... */);
})
.catch((err) => console.log(err));
解决方案
推荐阅读
- jquery - 无法使用 rest 更新共享点列表中的数据 [错误请求错误]
- python - Python用科学记数法显示5.26E-325是0,但5.26E-324是5e-324,为什么?
- tableau-api - 如何在 Tableau 中将固定长度的字符串转换为多列
- java - 使用 ACS 智能卡读卡器获取 Mifare Keys (A & B)
- java - 即使将 jar 添加到类路径中,也没有找到类定义错误
- python - 在 requirements.txt 中强制重新安装 pip
- android - 如何通过电子邮件在 android 应用程序中实现 otp 功能
- zip - 压缩中断时磁盘上压缩文件的完整性
- python - 什么都不做的Django错误?
- ios - 推送通知 IOS:标准有效负载格式