Node.js – 外部JS和CSS文件(只是使用node.js不表示)

我试图学习node.js并碰到了一些障碍。

我的问题是,我似乎无法加载到HTML文件的外部CSS和JS文件。

GET http://localhost:8080/css/style.css 404 (Not Found) GET http://localhost:8080/js/script.css 404 (Not Found) 

(这是当所有的文件都在应用程序的根目录)

我被告知有点模仿下面的应用程序结构,添加公共目录的路线,以允许networking服务器提供外部文件。

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

 domain.com app/ webserver.js public/ chatclient.html js/ script.js css/ style.css 

所以我的webserver.js脚本是在应用程序的根,我想要访问的一切都在“公共”。

我也看到这个例子使用path.extname()来获取位于path中的任何文件扩展名。 (见最后的代码块)。

所以我试图结合新的网站结构和这个path.extname()的例子,让networking服务器允许访问任何文件在我的公共目录,所以我可以呈现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); } }); 

在公开的情况下,我试图通过var extname = mypath.extname(path)获得这个目录中的任何文件夹/文件。 类似于我提供的链接。

但是,当我login时,“extname”是空的。

任何人都可以build议我可能需要添加或啾啾在这里? 我知道这可以在Express中轻松完成,但是我想知道如何依靠Node实现同样的事情。

我很感激这方面的帮助。

提前致谢。

你的代码有几个问题。

  1. 您的服务器不会运行,因为您尚未指定要侦听的端口。
  2. 正如Eric指出的,您的案件情况将会失败,因为“公开”不会出现在url中。
  3. 你在js和css响应中引用了一个不存在的variables'content',应该是'data'。
  4. 你的CSS内容types的标题应该是文本/ CSS而不是文本/ JavaScript
  5. 在主体中指定'utf8'是不必要的。

我已经重新编写了你的​​代码。 注意我不使用大小写/开关。 我更喜欢更简单,如果这是你的偏好,你可以把它们放回去。 我的重写中没有必要使用url和path模块,所以我删除了它们。

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

您可能需要考虑使用像express这样的服务器框架,它允许您设置一个“public”目录来自动路由静态文件

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

这种框架的廉价开销真的值得有效地“重塑车轮”

public不会出现在客户端所请求的URL中,所以myPath上的开关总是通过。

您可以考虑查看Connect中提供的静态中间件。 看看静态的源代码可能会给你一些关于如何使用node.js代码(如果你想学习如何做,而不使用现有的库)的想法。

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

这些是相反的。 应该:

  var extension = path.extname(mypath); 

我也可以避免使用variables名称的函数名称。

自动更新文件更改,延迟更新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}/`); });