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)
(これは、すべてのファイルがアプリのルートにあったときでした)
次のアプリの構造をいくらか模倣し、パブリックディレクトリのルートを追加して、ウェブサーバーが外部ファイルを提供できるようにするように言われました。
私のアプリの構造はそうです
domain.com
app/
webserver.js
public/
chatclient.html
js/
script.js
css/
style.css
したがって、私のwebserver.jsスクリプトはアプリのルートにあり、アクセスしたいものはすべて「public」にあります。
また、path.extname()を使用して、パスにあるファイル拡張を取得するこの例も見ました。(最後のコードブロックを参照してください)。
そこで、新しいサイト構造とこのpath.extname()の例を組み合わせて、Webサーバーがパブリックディレクトリ内の任意のファイルにアクセスできるようにして、外部のjsファイルとcssファイルを参照するhtmlファイルをレンダリングできるようにしました。 。
私の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(path);を介して、このディレクトリ内の任意のフォルダー/ファイルを取得しようとしています。私が提供したリンクに似ています。
しかし、現時点では、コンソールでログに記録すると「extname」は空になります。
誰かが私がここに追加またはtweekする必要があるかもしれないものをアドバイスできますか?これはExpressで簡単に実行できることは承知していますが、Nodeだけに依存して同じことを実現する方法を知りたいと思います。
これについての助けに感謝します。
前もって感謝します。