繁体   English   中英

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

[英]Correct way to Load JS Files With HTML files through NodeJS

我不能将服务的defualt.htm页面的头部内容包含在“工作”中。 dom中的html加载,只有CSS和JS文件失败。 还有更好的选择吗? 我喜欢将解决方案保留在NodeJS中,但也可以打开socket.io并表达。

谢谢,下面是我正在使用的。

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

Default.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>

您的Javascript和样式失败,因为它们不存在。 您当前的网络服务器只发送一条路由,即根路由。 相反,您需要允许使用多个路线。 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的文件系统结构的文件夹。

好吧,您正在为所有请求提供default.htm文件。 因此,当浏览器请求objects/js/jquery.min.js ,您的服务器将返回default.htm的内容。

你应该考虑使用express或其他框架。

我也要在这里扔两分钱。

我解决服务静态文件同样问题的方法是我开始使用Paperboy模块,现在不赞成使用Send模块。

Anyhoo,我解决它的方式是在它进入我的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);
    });
}

你最好使用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 
    }
});

索引是一个玉石模板页面。它呈现为静态HTML,并且与express表现相当不错。

对于所有页面的全局静态标头,您可以制作这样的模板并将其包含在任何页面中。

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使用static_header和自己的动态头文件及其自己的脚本。

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

将两个文件放在views文件夹中并准备好滚动。

尝试这个怎么样:

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/');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM