【问题标题】:Remove filename from URL with Express使用 Express 从 URL 中删除文件名
【发布时间】:2021-07-19 10:13:58
【问题描述】:

当我在 Nodejs 上托管我的前端时,我使用 app.use(express.static(path.join(__dirname, "public")));。但是,这使我将 HTML 文件的名称放在 URL 的末尾;例如,localhost:3000/index.html。

如何让它在基本 URL 上显示前端,在本例中为“localhost:3000/”。我附上了我的 Nodejs 代码的一部分。如有任何帮助,我将不胜感激,并在此先感谢您。

var path = require('path');
var express = require('express');
const app = express();
const port = process.env.PORT || '3000';

app.use(express.json());

app.use((req, res, next) => {
    console.log(req.path);
    next();
});

app.use(express.static(path.join(__dirname, "public")));

app.listen(port, () => console.log("Server is ready"));

【问题讨论】:

  • 那么你在后端服务器上使用 index.html 作为首页吗?
  • 你的前端是什么?是框架还是更多的html模板?

标签: node.js express web


【解决方案1】:

您可以使用路由路径和 sendFile 方法:

app.get("/", function(req,res) {
  res.sendFile("index.html", {root: path.join(__dirname, "public")})
})

More details here

【讨论】:

    【解决方案2】:

    这就是你应该做的。

    //for static files like css and html
    
    app.use('/static', express.static(path.resolve(__dirname, path to css and js)));
    
    
    app.get('/*', (req, res)=>{
       res.sendFile(path.join(__dirname, 'path to your html file'))
    })
    

    【讨论】:

    • 如何将我的 Javascript 和 CSS 文件添加到 HTML?
    • 修改了答案。它应该是保存你的 css 和 js 文件的文件夹
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 2017-07-02
    • 2014-04-22
    • 2013-03-14
    相关资源
    最近更新 更多