【问题标题】:NodeJS not serving static htmlNodeJS 不提供静态 html
【发布时间】:2017-09-06 21:02:09
【问题描述】:

我在节点服务器上提供我的 html 文件时遇到问题。

“index.js”中的代码如下所示:

const express = require('express');
const app = express();
var path = require('path');

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

app.get('/', function (req, res) {
  res.sendFile('views/home.html');
});

app.listen(8081, function () {
  console.log('Magic is happening on port 8081!');
});

这是我的文件结构的图片:

当我运行服务器时,它给了我这个错误:

TypeError: path must be absolute or specify root to res.sendFile

最后我需要一个可以服务多个不同页面的服务器,这只是我服务的第一页(如果第一页不起作用,那就没有意义了..)

我做错了什么?

【问题讨论】:

  • 我对node.js一无所知,但是尝试将路径更改为'/views/home.html'
  • @Chrisstar,当我这样做时,我得到:错误:ENOENT:没有这样的文件或目录,stat '/views/home.html'。
  • 请添加目录结构截图
  • 会发生什么?您是否在控制台中看到错误。浏览器显示什么,什么状态码?
  • 附注:为什么写path.join(__dirname + '/public'),应该是path.join(__dirname, 'public')

标签: html node.js express static


【解决方案1】:

好的,所以我想出了一个解决方案。

我把整个设置改成了这个

var express     = require('express');
var app         = express();
var port        = process.env.PORT || 8081;

var path        = require('path');
var http        = require('http');
var router      = express.Router();
//var data        = require('./routes/data');

// Setting the view engine and defining paths
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));

require('./routes/routes')(app);

app.listen(port, function () {
    console.log('server running on port ' + port);
});

module.exports = app;

现在正在按照我想要的方式工作。不确定它是最佳还是完美,但我认为它可以完成这项工作。

谢谢大家的帮助!!

【讨论】:

    【解决方案2】:

    要使这段代码工作:

    const express = require('express');
    const app = express();
    var path = require('path');
    
    app.use(express.static(path.join(__dirname, 'public')));
    
    app.get('/', function (req, res) {
      res.sendFile('views/home.html');
    });
    
    app.listen(8081, function () {
      console.log('Magic is happening on port 8081!');
    });
    

    你必须有这样的目录结构:

    views
      |-home.html
    public
      |- some files here
    index.js
    

    【讨论】:

      【解决方案3】:

      文档和错误告诉你sendFile [...]Unless the root option is set in the options object, path must be an absolute path to the file[...] (res.sendFile(path [, options] [, fn]))

      所以你必须写:

      res.sendFile(path.join(__dirname, 'public/views/home.html'))
      

      【讨论】:

      • 这行得通,但我的印象是还有其他方法可以做到这一点,考虑到除了“home.html”页面之外还有其他几个页面。
      • @henrikbossart 好吧,您在问题中是这样写的。您的问题不是如何解决其他几个页面的问题。但是为什么你的代码不提供给定的文件。
      • 对不起,我的错..我需要这个工作几页
      • @henrikbossart 它应该如何工作?目前yourdomain.tld/view/home.html 将在该目录中提供该文件或任何其他文件。如果这不是您想要的路径,请添加另一个 express.static 例如使用path.join(__dirname, 'public/views/'),以便路径为yourdomain.tld/home.html。但是从问题中不清楚请求路径应该如何对应于所服务的文件。
      【解决方案4】:

      运行此代码,将 html 文件保存在同一文件夹中,例如:index.html 在浏览器中,localhost:9000/index.html

          var http = require("http");
          var fs = require("fs");
          var port = 9000;
      
          //create server
          http.createServer(function(req,resp){
              reqUrl = req.url;
              var day = reqUrl.slice(1,reqUrl.length-1);
              file = reqUrl;
              callPage(req,resp,file);
          }).listen(port); 
      
      
          function callPage(req,resp,fileName){
      
              fileName = reqUrl.slice(1,reqUrl.length);
              console.log(fileName)
              fs.readFile(fileName,function(err,html){
                  if(err){
                      throw err;
                  }
      
                  resp.writeHead(200,{"content-type":"text/html"});
                  resp.write(html);
                  resp.end();
              });
      
          }
      

      【讨论】:

        【解决方案5】:

        对于您的目录结构,您的代码必须如下所示

        app.use(express.static(path.join(__dirname, 'public', 'views'), {index: 'home.html'})); app.use(express.static(path.join(__dirname, 'public'))); Serving static files examples

        【讨论】:

          【解决方案6】:

          这是我的建议:

          1) 将views 文件夹移动到与index.js 相同的位置

          2) 更新index.js的代码:

          const 
              DEBUG_MODE = (process.env.DEBUG == 1),
              express = require('express'),
              app = express();
          
          /* DEFINE VIEW RENDERER */
          app.set('view cache', !DEBUG_MODE);
          app.engine('html', require('ejs').renderFile);
          app.set('view engine', 'html');
          
          /* DEFINE VIEW FILES LOCATION */
          app.set('views', __dirname + '/views');
          
          /* KEEP STATIC FILES IN SOME CONSTANT (GROUPED) PLACE, EX.: /assets */
          app.use('/assets/css', express.static(__dirname + '/public/css'));
          app.use('/assets/images', express.static(__dirname + '/public/images'));
          
          /* RENDER home VIEW FOR ROOT REEQUEST */    
          app.all('/', (req, res) => res.render('home'));
          
          app.listen(8081, function () {
            console.log('Magic is happening on port 8081!');
          });
          

          提供视图文件是 express 应用程序的工作,只需调用 res.render('view-name'); 即可完成(没有扩展名,因为 app.engine('html', ...); 中已经定义了

          附:如果您需要示例:https://bitbucket.org/num8er/sum-az-website/src

          【讨论】:

          • 导致“无法获取 /home.html”
          • @henrikbossart 如果您想要请求后端部分数据的前端部分,请制作 2 个应用程序:前端应用程序、后端 API
          猜你喜欢
          • 2015-08-20
          • 2021-09-07
          • 1970-01-01
          • 1970-01-01
          • 2014-08-26
          • 2012-09-06
          • 2019-03-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多