NodeJS 如何从外部Express Router文件响应html文件

qvk1mo1f  于 2023-06-29  发布在  Node.js
关注(0)|答案(1)|浏览(122)

我如何从外部呈现任何HTML文档与express.router()。
我的app.js:

const express = require("express");
const fs = require("fs");
const https = require("https");
const path = require("path");

const app = express();
const https_port = 443;

app.use(express.static(path.join(__dirname + '/public')));
const homeRoute = require('./routes/home')
const userRoute = require('./routes/user')
app.use('/user', userRoute)
app.use('/home', homeRoute)

//Create server
https
  .createServer(
    {
      key: fs.readFileSync("ssl/privkey.pem"),
      cert: fs.readFileSync("ssl/cert.pem"),
    },
      app
  )
  .listen(https_port, () => {
    console.log('https server is running on port 443')
  });

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

my home.js:

const express = require("express");
const router = express.Router()

router.get("/", (req,res) => {
   // res.send("Home site")
   res.sendFile(__dirname + '/login.html');
})

router.post("/", (req,res) => {
    res.send("Home site")
})

router.put("/", (req,res) => {
    res.send("Home site")
})

router.delete("/", (req,res) => {
    res.send("Home site")
})

module.exports = router;

文件夹结构为:

public
   --> index.html
   --> login.html
routes
   --> home.js
   --> user.js
app.js

如果我在浏览器中输入http://<MYADRESS>/home,我会在浏览器中收到此消息:Error: ENOENT: no such file or directory, stat '/root/PWA/routes/login.html
这也是可以理解的,因为login.html文件不在路由文件夹中。但是我如何从我的home.js路由器文件调用login.html文件?
我在Express文档中找到了redirect()方法,使用...res.redirect('/login.html');...可以工作。
但这是正确的方式吗?

tpxzln5u

tpxzln5u1#

app.js

const express = require('express');
const fs = require('fs');
const path = require('path');
const homeRoute = require('./routes/home');

const app = express();

app.use(express.static(path.join(__dirname + '/public')));
app.use('/home', homeRoute);

app.get('/', (req, res) => {
    res.sendFile(path.resolve(__dirname, './public/index.html'));
});

app.listen(3000, () => {
    console.log('https server is running on port 3000');
});

routes/home.js

const express = require('express');
const path = require('path');
const router = express.Router();

router.get('/', (req, res) => {
    res.sendFile(path.resolve(__dirname, '../public/login.html'));
});

module.exports = router;

您可以通过以下方式访问index页面:

  • 静态文件:http://localhost:3000/index.html
  • 路线:http://localhost:3000/

通过以下方式访问login页面:

  • 静态文件:http://localhost:3000/login.html
  • 路线:http://localhost:3000/home

相关问题