通过NodeJS正确加载HTML文件中的JS文件的方法

6
我无法让默认的defualt.htm页面头部包含的内容“工作”。HTML在DOM中加载,但CSS和JS文件都失败了。是否有更好的替代方案?我希望将解决方案保持在NodeJS内,但也可以考虑socket.io和express。谢谢!以下是我正在使用的内容。 使用NodeJS提供页面
var http = require('http'),
fs = require('fs');

fs.readFile(__dirname+'/default.htm', function (err, html) {
    if (err) {
        throw err; 
    }       
    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(port.number);
});

默认.html页面

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" href="objects/css/site.css" type="text/css" />
    <script src="objects/js/jquery.min.js" type="text/javascript"></script>
    <script src="objects/js/site.min.js" type="text/javascript"></script>
</head>

<body></body>    

</html>

如果你想自己编写代码,可以查看 https://github.com/felixge/node-paperboy 或者 https://github.com/visionmedia/send 这两个 Node.js 模块。它们可以帮助你传送静态文件,例如 CSS、JS 和图片。 - Henrik Andersson
我的问题是,为什么你要使用node.js来提供静态文件?使用nginx或类似的工具。所有非用户界面任务都不应该在用于提供动态内容的同一事件循环中完成。 - Gabriel Llamas
5个回答

4

你的Javascript和样式表无法加载,因为它们不存在。你当前的Web服务器只发送了一个路由,即根路由。你需要允许使用多个路由。ExpressJS可以更简单地完成这项工作,但在没有它的情况下仍然很有可能实现。

    var http = require('http');
    var fs   = require('fs');


    var server = http.createServer(function(request, response){
       var header_type = "";
       var data        = "";
       var get = function (uri, callback) {
           // match `request.url` with uri with a regex or something.
           var regex = uri;
           if (request.url.match(regex)) {
               callback();
           }
       };    

       var render = function (resource) {
           // resource = name of resource (i.e. index, site.min, jquery.min)
           fs.readFile( __dirname + "/" + resource, function(err, file) {
              if (err) return false; // Do something with the error....
              header_type = ""; // Do some checking to find out what header type you must send.
              data = file;
           }
       };

       get('/', function(req, res, next) {
           // Send out the index.html
           render('index.html');
           next();
       });


       get('/javascript.min', function(req, res, next) {
          render('javascript.js');
          next();
       });


    });

    server.listen(8080);

这可能会让你有所启发,但你需要自己实现一些东西,比如next()。这是一个相当简单但有效的解决方案。
另一种响应静态文件的解决方案是在http.createServer回调函数中创建一个捕获器。在get方法中,如果uri不匹配,则在public文件夹中查找与完整uri匹配的文件系统结构。

3
尝试这个怎么样:
var http = require('http');
var fs = require('fs');
var path = require('path');

http.createServer(function (request, response) {
console.log('request starting...');

var filePath = '.' + request.url;
if (filePath == './')
    filePath = './index.html';

var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
    case '.js':
        contentType = 'text/javascript';
        break;
    case '.css':
        contentType = 'text/css';
        break;
    case '.json':
        contentType = 'application/json';
        break;
    case '.png':
        contentType = 'image/png';
        break;      
    case '.jpg':
        contentType = 'image/jpg';
        break;
    case '.wav':
        contentType = 'audio/wav';
        break;
}

fs.readFile(filePath, function(error, content) {
    if (error) {
        if(error.code == 'ENOENT'){
            fs.readFile('./404.html', function(error, content) {
                response.writeHead(200, { 'Content-Type': contentType });
                response.end(content, 'utf-8');
            });
        }
        else {
            response.writeHead(500);
            response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
            response.end(); 
        }
    }
    else {
        response.writeHead(200, { 'Content-Type': contentType });
        response.end(content, 'utf-8');
    }
});

}).listen(8125);
console.log('Server running at http://127.0.0.1:8125/');

3
我也想发表一下我的观点。
当我面临静态文件的同样问题时,我开始使用 Paperboy 模块解决该问题。现在,该模块已被 Send 模块代替。
无论如何,我解决它的方式是在 GET 方法之前“劫持”请求并检查其路径。
我“劫持它”的方式如下:
self.preProcess(self, request, response);

并且

preProcess: function onRequest(app, request, response){ //DO STUFF }

如果路径包含STATICFILES目录,则我会采用不同的文件服务方式,否则我会使用“html”路径。下面是preProcess()函数的//DO STUFF部分。
var path = urllib.parse(request.url).pathname;
if(path.indexOf(settings.STATICFILES_DIR) != -1) {
    path = settings.STATICFILES_DIR;
    requestedFile = request.url.substring(request.url.lastIndexOf('/') + 1, request.url.length);
    return resolver.resolveResourceOr404(requestedFile, request, response);
}

可能有更好的方法,但对于我需要完成的事情,这种方法非常有效。

使用Paperboy模块,然后使用resolver.resolveResourceOr404();函数来提供文件,如下所示:

resolveResourceOr404 : function (filename, httpRequest, httpResponse) {
    var root = path.join(path.dirname(__filename), '');

    paperboy.deliver(root, httpRequest, httpResponse)
    .error(function(e){
        this.raise500(httpResponse);
    })
    .otherwise(function(){
        this.raise404(httpResponse);
    });
}

这正是我想要的,但我明白我需要根据请求URL加载。 - sia

3

你现在的问题是所有请求都返回了 default.htm 文件。所以,当浏览器请求 objects/js/jquery.min.js 时,服务器会返回 default.htm 的内容。

你应该考虑使用 express 或其他框架来解决这个问题。


2

对于这种事情,最好使用Express。

像这样就可以完成任务。

App.js

var express = require('express')
  , http = require('http')
  , path = require('path');

var app = express();

//Configure Your App and Static Stuff Like Scripts Css
app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views'); // Your view folder
  app.set('view engine', 'jade');  //Use jade as view template engine
  // app.set("view options", {layout: false});  
  // app.engine('html', require('ejs').renderFile); //Use ejs as view template engine
  app.use(express.logger('dev'));

  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser());
  app.use(app.router); 
  app.use(require('stylus').middleware(__dirname + '/public')); //Use Stylus as the CSS template engine
  app.use(express.static(path.join(__dirname, 'public'))); //This is the place for your static stuff
});


app.get('/',function(req,res){
  res.render('index.jade',{
    title:"Index Page 
    }
});

Index是一个jade模板页面,可以与express很好地配合,渲染为静态html。

如果要为所有页面添加全局静态标题,您可以创建如下模板,并在任何页面中包含它。

static_header.jade

  doctype 5
html
  head
    title= title
    script(src='/javascripts/jquery-1.8.2.min.js')   
    block header 
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    block content

最后是您的index.jade文件,它使用了静态标题和自己的动态标题以及其自己的脚本。

extends static_header

block header
  script(src='/javascripts/jquery-ui-1.9.1.custom.js')
  script(src='http://jquery-ui.googlecode.com/svn/trunk/ui/i18n/jquery.ui.datepicker-tr.js')
  link(rel='stylesheet',href='/stylesheets/jquery-ui-1.9.1.custom.min.css')
block content
  h1= title

将这两个文件放在你的视图文件夹中,准备好了就可以使用了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接