私は次のコードを書きました:
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に行くべきです