javascript - 如何使用 NodeJS 提供多个 html 文件

标签 javascript node.js mongodb express mongoose

我使用nodeJS创建了一个mongoDB表单,并且可以提供注册页面,但是当我单击任何其他链接转到其他页面时,它会抛出“Cannot GET/index.html”。我不确定如何使用 Nodejs 提供多个文件。

var express = require("express");
var app = express();
var port = 3000;
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/ClubArchive_Users");
var nameSchema = new mongoose.Schema({
     fname: String,
     lname: String,
     email: String, 
     uname: String,
     pwd :String
});
var User = mongoose.model("User", nameSchema);

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

app.post("/addname", (req, res) => {
    var myData = new User(req.body);
    myData.save()
        .then(item => {
            res.sendFile(__dirname + "/index.html");
        })
        .catch(err => {
            res.status(400).send("Unable to save to database");
        });
});

app.listen(port, () => {
    console.log("Server listening on port " + port);
});

最佳答案

node.js 本身不提供任何内容。因此,您希望服务器响应的任何 URL 都必须在 Express 中具有相应的路由。您可以使用以下代码单独对每个代码进行编码

app.get(someURLPath, someHandler);

或者,您可以使用 express.static() 中间件提供位于目录层次结构中的一组静态页面。

为了更具体地帮助您,我们需要:

  1. 查看您要提供的页面的总体列表
  2. 了解哪些是静态 HTML 页面,哪些是动态
  3. 了解它们在本地文件系统中的位置
  4. 查看您希望每个页面使用哪些网址

可以查看express.static的通用教程 herehere .

when I click on any other links to go to other pages, it throws "Cannot GET /index.html" for example. I am unsure of how to serve multiple files using nodejs.

您需要教您的 Node.js 服务器如何响应这些其他链接。要么为每个页面创建一个自定义路由,要么对于静态页面,使用 express.static(),以便它可以通过一行中间件来提供一堆静态页面。

关于javascript - 如何使用 NodeJS 提供多个 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58886063/

相关文章:

javascript - 无法让工具栏显示在 Node Webkit 中

javascript - Raphaël 的问题以及删除 svg 中的对象

javascript - socket.io 连接多个进程

javascript - 保存 Mongoose 文档时出现版本错误

python - Mongoengine Flask 获取 dbstats

javascript - 为什么 "Facebook Comments"iFrame 在使用 CSS 'display: none' 加载到容器中时具有不同的高度?

javascript - 如何从一个jsp页面到另一个jsp页面获取select标签中给出的值

node.js - Nodejs 强大的更改文件名和时间戳

json - mongoimport语法错误意外标识符

mongodb - 如何在 Sails 中创建应用程序时覆盖 Mongodb 中的对象 ID