【问题标题】:app.use express serve multiple htmlapp.use express 服务多个 html
【发布时间】:2015-11-22 07:54:21
【问题描述】:

我正在为我的网站使用 node.js 和 express。当用户单击 index.html 中的链接时,我需要能够引导用户。 我有三个页面:index.html、presentation.html、join.html 都在公共文件夹中。 这就是我在 server.js 中进行路由的方式:

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

app.use(express.bodyParser({ keepExtensions: true, uploadDir: __dirname + '/_tmp'}));

这就是我在 index.html 中编写链接的方式:

<a class="btn" href="/presentation">Presentation</a>
<a class="btn" href="/join">Join</a>

当我运行服务器时,我得到了 index.html,但是当我单击其中一个链接导航到其他页面时,我得到了这个错误:

Cannot GET /presentation

当我尝试添加到 server.js 时:

app.get('/presentation',function(req,res){
  res.render('public/presentation.html' , { root : __dirname});
});

我收到此错误:

TypeError: undefined is not a function

这是我的应用布局:

App
/pulic
      indx.html
      join.html
      presentatio.html
server.js

如何启用导航?

【问题讨论】:

    标签: node.js html express web


    【解决方案1】:

    我用的是我的,效果很好

    const express = require("express");
    const app = express();
    const router = express.Router();
    const path = require('path');
    
    app.use(express.static(path.join(__dirname, 'public')));
    
    var publicPath = path.join(__dirname, 'public');
    
    
    
    
    router.get("/", function (req, res) {
        res.sendFile(path.join(__dirname, "/"));
    });
    
    
    app.get('/new_deposit', function (req, res) {
        res.sendfile(publicPath + '/new_deposit.html');
    });
    

    【讨论】:

      【解决方案2】:

      按照配置,您可以直接将 HTML 文件作为文件href="/join.html" 访问。

      如果你想为静态文件使用路由,试试这个:

      var publicPath = path.join(__dirname, 'public');
      
      app.get('/test', function (req, res) {
        res.sendfile(publicPath + '/test.html');
      });
      

      【讨论】:

        【解决方案3】:

        我在路线中发现了错误: 我正在使用 res.render 或 res.sendFile 当我使用 res.sendfile 时,它​​工作得很好。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-07-04
          • 1970-01-01
          • 2013-06-11
          • 2016-10-25
          • 1970-01-01
          • 2015-01-29
          相关资源
          最近更新 更多