NodeJS不提供静态html

时间:2017-09-06 12:05:19

标签: html node.js express static

我在节点服务器上提供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!');
});

以下是我的文件结构图片:

File structure

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

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

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

我做错了什么?

6 个答案:

答案 0 :(得分: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;

现在按照我想要的方式工作。不确定它是最佳的还是完美的,但我认为它能起作用。

谢谢大家的帮助!!

答案 1 :(得分:0)

对于你的目录结构,你的代码必须是

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

答案 2 :(得分:0)

要使此代码有效:

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 :(得分:0)

文档和错误告诉您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'))

所以你必须写:

  @Override
public boolean onOptionsItemSelected(MenuItem item) {

    // handle arrow click here
    if (item.getItemId() == android.R.id.home) {
        if(fromString.equalsIgnoreCase("second")){
            //finish();
            Intent intent = new Intent(getApplicationContext(),MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }else if(fromString.equalsIgnoreCase("first")){

            finish(); // close this activity and return to preview activity (if there is any)

        }
    }
    return super.onOptionsItemSelected(item);
}

答案 4 :(得分:0)

运行此代码,将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 :(得分:0)

以下是我的建议:

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!');
});

提供视图文件是快递应用程序的工作,只需调用res.render('view-name');(无扩展名,cuz已在app.engine('html', ...);中定义

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

相关问题