我使用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()
中间件提供位于目录层次结构中的一组静态页面。
为了更具体地帮助您,我们需要:
- 查看您要提供的页面的总体列表
- 了解哪些是静态 HTML 页面,哪些是动态
- 了解它们在本地文件系统中的位置
- 查看您希望每个页面使用哪些网址
可以查看express.static的通用教程 here和 here .
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/