Node.js-外部js和CSS文件(仅使用Node.js而不是express)

Node.js-外部js和CSS文件(仅使用Node.js而不是express),node.js,Node.js,我试图学习node.js,但遇到了一些障碍 我的问题是,我似乎无法将外部css和js文件加载到html文件中 GET http://localhost:8080/css/style.css 404 (Not Found) GET http://localhost:8080/js/script.css 404 (Not Found) (当时所有文件都位于应用程序的根目录下) 我被告知要模拟一下下面的应用程序结构,为public dir添加一个路由,以允许web服务器为外部文件提供服务 我的应

我试图学习node.js,但遇到了一些障碍

我的问题是,我似乎无法将外部css和js文件加载到html文件中

GET http://localhost:8080/css/style.css 404 (Not Found) 
GET http://localhost:8080/js/script.css 404 (Not Found) 
(当时所有文件都位于应用程序的根目录下)

我被告知要模拟一下下面的应用程序结构,为public dir添加一个路由,以允许web服务器为外部文件提供服务

我的应用程序结构是这样的

domain.com
  app/
    webserver.js

  public/
    chatclient.html

    js/
      script.js

    css/
      style.css
因此,我的webserver.js脚本位于应用程序的根目录中,我想要访问的所有内容都位于“public”中

我还看到它使用path.extname()获取路径中的任何文件扩展名。(请参见最后一个代码块)

因此,我尝试将新的站点结构与path.extname()示例结合起来,让Web服务器允许访问我的公共目录中的任何文件,这样我就可以呈现html文件,该文件引用外部js和css文件

我的webserver.js看起来像这样

var http = require('http')
, url = require('url')
, fs = require('fs')
, path = require('path')
, server;

server = http.createServer(function(req,res){

  var myPath = url.parse(req.url).pathname;

    switch(myPath){

      case '/public':

        // get the extensions of the files inside this dir (.html, .js, .css)
        var extname = mypath.extname(path);

          switch (extname) {

            // get the html
            case '.html':
              fs.readFile(__dirname + '/public/chatclient.html', function (err, data) {
                if (err) return send404(res);
                res.writeHead(200, {'Content-Type': 'text/html'});
                res.write(data, 'utf8');
                res.end();
              });
            break;

            // get the script that /public/chatclient.html references
            case '.js':
              fs.readFile(__dirname + '/public/js/script.js', function (err, data) {
                if (err) return send404(res);
                res.writeHead(200, { 'Content-Type': 'text/javascript' });
                res.end(content, 'utf-8');
                res.end();
              });
            break;

            // get the styles that /public/chatclient.html references
            case '.css':
              fs.readFile(__dirname + '/public/css/style.css', function (err, data) {
                if (err) return send404(res);
                res.writeHead(200, { 'Content-Type': 'text/javascript' });
                res.end(content, 'utf-8');
                res.end();
              });
          }
          break;

          default: send404(res);
        }
    });
在public的情况下,我试图通过 var extname=mypath.extname(路径); 类似于我提供的链接

但目前,当我在控制台上记录“extname”时,它是空的

有人能告诉我需要在这里添加什么吗? 我知道这在Express中很容易实现,但我想知道如何仅依靠Node实现同样的功能

我非常感谢你在这方面的帮助


提前感谢。

public
不会出现在客户端请求的URL中,因此myPath上的切换总是会失败。

您可能希望研究使用服务器框架,例如,它允许您设置“public”目录以自动路由静态文件

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

<> P.>这样一个框架的廉价开销真的很值得有效地“重新发明轮子”

< P>你可以考虑查看连接中提供的中间件。查看Static的源代码可能会让您了解如何使用node.js代码实现这一点(如果您想了解如何在不使用现有库的情况下实现这一点)。

您的代码存在一些问题

  • 您的服务器将不会运行,因为您尚未指定要侦听的端口
  • 正如Eric指出的,您的案例条件将失败,因为“public”不会出现在url中
  • 您正在js和css响应中引用一个不存在的变量“content”,应该是“data”
  • css内容类型标题应该是text/css,而不是text/javascript
  • 在正文中指定“utf8”是不必要的
  • 我已经重新编写了你的代码。 请注意,我不使用case/switch。我喜欢简单得多的if和else,如果你喜欢的话,你可以把它们放回去。url和路径模块在我的重写中不是必需的,所以我已经删除了它们

    var http = require('http'),
        fs = require('fs');
    
    http.createServer(function (req, res) {
    
        if(req.url.indexOf('.html') != -1){ //req.url has the pathname, check if it conatins '.html'
    
          fs.readFile(__dirname + '/public/chatclient.html', function (err, data) {
            if (err) console.log(err);
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.write(data);
            res.end();
          });
    
        }
    
        if(req.url.indexOf('.js') != -1){ //req.url has the pathname, check if it conatins '.js'
    
          fs.readFile(__dirname + '/public/js/script.js', function (err, data) {
            if (err) console.log(err);
            res.writeHead(200, {'Content-Type': 'text/javascript'});
            res.write(data);
            res.end();
          });
    
        }
    
        if(req.url.indexOf('.css') != -1){ //req.url has the pathname, check if it conatins '.css'
    
          fs.readFile(__dirname + '/public/css/style.css', function (err, data) {
            if (err) console.log(err);
            res.writeHead(200, {'Content-Type': 'text/css'});
            res.write(data);
            res.end();
          });
    
        }
    
    }).listen(1337, '127.0.0.1');
    console.log('Server running at http://127.0.0.1:1337/');
    
    这些是相反的。应该是:

       var extension = path.extname(mypath);
    

    如果可以避免的话,我也不使用函数名作为变量名。

    更改时自动更新文件,延迟更新1秒。 格式:app.js | index.htm | style.css

    // packages
    const http = require('http');
    const fs = require('fs');
    // server properties
    const hostname = '127.0.0.1';
    const port = 3000;
    const timer = 300;
    
    //should trigger atualize function every timer parameter
    let htmlfile = '';
    let cssfile = '';
    let jsfile = '';
    
    uptodate();
    
    // should read file from the disk for html
    function uptodate()
    {
      console.log(1);
       fs.readFile('./index.html', function (err, html) {
        if (err) {
          throw err; 
        }       
        htmlfile = html;
      });
      // should read css from the disk for css
       fs.readFile('./style.css', function (err, html) {
        if (err) {
          throw err; 
        }       
        cssfile = html;
      });
    
      // should read js file from the disk
      fs.readFile('./app.js', function (err, html) {
        if (err) {
          throw err; 
        }       
        jsfile = html;
      });
      setTimeout(function(){ uptodate(); }, 1000);
    }
    const server = http.createServer((req, res) => {
      res.statusCode = 200;
    
      // should send css and js
      if(req.url.indexOf('.css') != -1){ //req.url has the pathname, check if it conatins '.js'
       res.writeHead(200, {'Content-Type': 'text/css'});
       res.write(cssfile);
       res.end();
       return;
      }
      if(req.url.indexOf('.js') != -1){ //req.url has the pathname, check if it conatins '.js'
       res.writeHead(200, {'Content-Type': 'text/javascript'});
       res.write(jsfile);
       res.end();
       return;
      }
      // should send html file via request
      res.writeHeader(200, {"Content-Type": "text/html"});  
      res.write(htmlfile);
      res.end();
    });
    
    // should send css and js 
    
    server.listen(port, hostname, () => {
      console.log(`Server running at http://${hostname}:${port}/`);
    });
    

    在调用
    send404()
    函数之前,请尝试打印出
    err
    的值,以查看实际错误是什么。谢谢,但正如我在最后所说的,我想知道如何在没有Express的情况下使用Node.js执行此操作。这对我来说是可行的,但我需要将“public”替换为“”
    // packages
    const http = require('http');
    const fs = require('fs');
    // server properties
    const hostname = '127.0.0.1';
    const port = 3000;
    const timer = 300;
    
    //should trigger atualize function every timer parameter
    let htmlfile = '';
    let cssfile = '';
    let jsfile = '';
    
    uptodate();
    
    // should read file from the disk for html
    function uptodate()
    {
      console.log(1);
       fs.readFile('./index.html', function (err, html) {
        if (err) {
          throw err; 
        }       
        htmlfile = html;
      });
      // should read css from the disk for css
       fs.readFile('./style.css', function (err, html) {
        if (err) {
          throw err; 
        }       
        cssfile = html;
      });
    
      // should read js file from the disk
      fs.readFile('./app.js', function (err, html) {
        if (err) {
          throw err; 
        }       
        jsfile = html;
      });
      setTimeout(function(){ uptodate(); }, 1000);
    }
    const server = http.createServer((req, res) => {
      res.statusCode = 200;
    
      // should send css and js
      if(req.url.indexOf('.css') != -1){ //req.url has the pathname, check if it conatins '.js'
       res.writeHead(200, {'Content-Type': 'text/css'});
       res.write(cssfile);
       res.end();
       return;
      }
      if(req.url.indexOf('.js') != -1){ //req.url has the pathname, check if it conatins '.js'
       res.writeHead(200, {'Content-Type': 'text/javascript'});
       res.write(jsfile);
       res.end();
       return;
      }
      // should send html file via request
      res.writeHeader(200, {"Content-Type": "text/html"});  
      res.write(htmlfile);
      res.end();
    });
    
    // should send css and js 
    
    server.listen(port, hostname, () => {
      console.log(`Server running at http://${hostname}:${port}/`);
    });