21

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だけに依存して同じことを実現する方法を知りたいと思います。

これについての助けに感謝します。

前もって感謝します。

4

6 に答える 6

31

コードにはいくつかの問題があります。

  1. リッスンするポートを指定していないため、サーバーは実行されません。
  2. エリックが指摘したように、「public」がURLに表示されないため、ケース条件は失敗します。
  3. jsおよびcss応答で存在しない変数「content」を参照しています。「data」である必要があります。
  4. csscontent-typeヘッダーはtext/javascriptではなくtext/cssである必要があります
  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/');
于 2012-08-27T00:42:05.653 に答える
8

静的ファイルを自動的にルーティングするための「パブリック」ディレクトリを設定できるexpressなどのサーバーフレームワークの使用を検討することをお勧めします

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

そのようなフレームワークの安価なオーバーヘッドは、効果的に「車輪の再発明」を行う努力の価値があります。

于 2012-08-26T23:16:42.500 に答える
2

publicクライアントによって要求されたURLには表示されないため、myPathのスイッチは常に失敗します。

于 2012-08-26T23:07:11.333 に答える
1

Connectで提供される静的ミドルウェアを検討することを検討できます。Staticのソースコードを見ると、node.jsコードでこれを行う方法についていくつかのアイデアが得られる可能性があります(既存のライブラリを使用せずにこれを行う方法を学びたい場合)。

于 2012-08-27T00:36:21.563 に答える
1

変更時にファイルを自動更新し、更新を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}/`);
});
于 2017-07-20T05:13:55.453 に答える
0
    // get the extensions of the files inside this dir (.html, .js, .css)
    var extname = **mypath**.extname(path);

これらは逆になります。する必要があります:

   var extension = path.extname(mypath);

また、回避できる場合は、変数名に関数名を使用しません。

于 2014-05-22T19:59:49.117 に答える