首页 > 解决方案 > 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));

标签: node.jsexpress

解决方案


推荐阅读