0

私は次のコードを書きました:

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

var fileName = 'site/index.html';
var encoding = 'utf-8';
var dataContent = "";

fs.readFile(fileName, encoding, function(error, data) {
    if(error) throw error;
    dataContent = data;
});

var requestListener = function(request, response) {
    response.writeHead(200, {
        'Content-Length': dataContent.length,
        'Content-Type': 'text/html',
        'connection': 'keep-alive',
        'accept': '*/*'
    });

    response.end(dataContent);
}

var server = http.createServer(requestListener, function(connect) {
    connect.on('end', function() {
        console.log('Server disconnected...');
    });
});

server.listen(8000, function() {
    console.log("Server is listening...");
});

サイト ディレクトリに 2 つのファイルがあります。

 1. index.html
 2. aboutus.html

ステップ 1: node コマンドを node runServer.js として使用して、上記のコードを実行します。

ステップ 2: ブラウザーを開いて、次の URL を入力しました。

http://localhost:8000/

ブラウザは index.html の内容を正しく表示しています。また、index.html ファイルには生のテキストが含まれており、別のファイル、つまり aboutus.html へのリンクが含まれています。

ステップ 3: aboutus.html のリンクをクリックすると、ブラウザは URL を次のように変更します。

http://localhost:8000/aboutus.html

aboutus.html のコンテンツは表示されず、代わりに index.html のコンテンツが表示されます

fileName 変数の内容が「site/index.html」であるため、これが発生していることはわかっています。したがって、ブラウザは index.html コンテンツをレンダリングしています

この動作を変更するにはどうすればよいですか? 私がexpress.jsを使用していない場合


ここで、次のコードにいくつかの変更を加えました。

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

var fileName = "site/index.html";
var encoding = 'utf-8';
var dataContent = "";

function readContentFile(fileName) {
    console.log(fileName);
    fs.readFile(fileName, encoding, function(error, data) {
        if(error) throw error;
        dataContent = data;
    });
}

readContentFile(fileName);

var requestListener = function(request, response) {

    filePath = request.url;    
    if(filePath!='/') {
        fileName = 'site' + filePath;
        readContentFile(fileName);
    }

    response.writeHead(200, {
        'Content-Length': dataContent.length,
        'Content-Type': 'text/html',
        'connection': 'keep-alive',
        'accept': '*/*'
    });

    response.end(dataContent);
}

var server = http.createServer(requestListener, function(connect) {



    connect.on('end', function() {
        console.log('Server disconnected...');
    });
});

server.listen(8000, function() {
    console.log("Server is listening...");
});

まだ機能していません。コードに何か問題がありますか。または私はexpress.jsに行くべきです

4

1 に答える 1

1

静的サーバーの例を作成しました

@ http://runnable.com/UUgnuT2wDj1UAGSeを見てください

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

http.createServer(function (req, res) {
  if (req.url === '/') {
    req.url = '/index.html';
  }
  var file = path.join(__dirname,req.url);
  path.exists(file, function (exists) {
    if (exists) {
      fs.stat(file, function (err, stats) {
        if(err) {
          throw err;
        }
        if (stats.isFile()) {
          res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
          fs.createReadStream(file).pipe(res);
        } else {
          res.writeHead(404);
          res.end('not found');
        }
      });
    } else {
      res.writeHead(404);
      res.end('not found');
    }
  });
}).listen( 8000 );

console.log('Server running on port ' + 8000);

注: これはノード 0.6.x を使用しており、API はそれ以来少し変更されており、path.exists ではなく fs.exists になっています。

于 2013-03-19T09:14:54.713 に答える