0

ノードjsは初めてです。リンクをたどっています。しかし、これは常に実行されているため、 index.htmlresponse.writeHead(404);を表示できません

これは私の Web サーバー ノードの js コードです。

var http = require('http');
var path = require('path');
var fs = require('fs');

http.createServer(function (request, response) {

    console.log('request starting...');

    var filePath = "."+request.url;
    if (filePath == './')
        filePath =  '/index.html';
    else
        console.log(request.url);
    var extname = path.extname(filePath);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
    }

    fs.exists( filePath, function (exists) {
        console.log(filePath);
        if (exists) {

            fs.readFile(filePath, function (error, content) {
                if (error) {
                    console.log(error);
                    response.writeHead(500);
                    response.end();
                }
                else {
                    response.writeHead(200, { 'Content-Type': 'text/html' });
                    response.end(content, 'utf-8');
                }
            });
        }
        else {
            response.writeHead(404);
            response.end();
        }
    });

}).listen(8125);

私の質問。

  1. これは index.html を表示していません。
  2. 応答または html ファイル ベースのさまざまな要求を送信するにはどうすればよいですか? 例: http://localhost:8125-> index.html http://localhost:8125/firstpage.html-> firstpage.html
  3. server.js (Web サーバー) を含む同じディレクトリに html ファイルを配置する必要がありますか?

cloud9 ideでも同じことを試しました。

ここに画像の説明を入力

SOで同様の問題を見つけました。しかし、それを修正する方法が明確にわかりませんでした。 Node.js - 基本ノード Web サーバーによって提供されていない Socket.io クライアント ファイル よろしくお願いします

4

1 に答える 1

1

1- はい、そうです。エラーを再現できます。私はチュートリアルに慣れていませんが、明らかに行filePath = '/index.html';filePath = './index.html';.

それ以外の場合、サーバーは「/index.html」、つまり現在のディレクトリではなく、ファイル システムのルートにある「index.html」という名前のファイルを探します。おそらく Windows OS では動作しますが、*nix ライクでは動作しません。を追加すると.、index.html が提供されます。

2- このためには、'url' node.js モジュールをインポートする必要があり、URL を解析する便利な方法にアクセスできます: http://nodejs.org/api/http.html#http_request_url 基本的に、fs.exist ...行の前に、以下を追加できます。

var requestedfile = urlparser.parse(request.url).pathname;
console.log("requested URL path name : " + requestedfile);

その後、さまざまなリクエストを処理できるようになります。

3- はい、できます。ドット「.」を追加するときは注意してください。問題 1. の「index.html」の前に、index.html への相対パスを指定していました (ファイルシステム上の server.js の場所を基準に)。したがって、この方法で他の相対パスを指定できます。

ページを現在のフォルダー以外の別のディレクトリ (例: /var/www/mysite) に保存する場合でも、この絶対パスを含む文字列変数をリクエスト パス名と連結することで、これらのページを提供できます。例:(興味はありますが)

var pagestorage = "/var/www/mysite/";
(...)
var pathname = urlparser.parse(request.url).pathname;
var requestfile = pagestorage + pathname;

更新されたファイルの完全なサンプルは次のとおりです。

 var http = require('http');
var path = require('path');
var fs = require('fs');
var urlparser = require('url');

http.createServer(function (request, response) {

    console.log('request starting...');

    var filePath = "."+request.url;
    if (filePath == './')
        filePath =  './index.html';
    else
        console.log(request.url);
    var extname = path.extname(filePath);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
    }

    // documentation at : http://nodejs.org/api/http.html#http_request_url
    var requestedfile = urlparser.parse(request.url).pathname;
    console.log("requested URL path name : " + requestedfile);

    fs.exists( filePath, function (exists) {
        console.log("looking up : " + filePath);
        if (exists) {

            fs.readFile(filePath, function (error, content) {
                if (error) {
                    console.log("error" + error);
                    response.writeHead(500);
                    response.end();
                }
                else {
                    response.writeHead(200, { 'Content-Type': 'text/html' });
                    response.end(content, 'utf-8');
                }
            });
        }
        else {
            response.writeHead(404);
            response.end();
        }
    });

}).listen(8125);

HTH

于 2013-02-16T15:54:39.173 に答える