iT邦幫忙

0

nodejs 載入 html + .js 問題

  • 分享至 

  • twitterImage

小弟(不是小妹 抱歉 XD)在使用nodejs的時候 遇到了一個問題
想請問各位前輩 就是呢 想將現有的網站 直接移植到nodejs上

所以呢 我目前的網站架構有 index.html 及
若干個index.html中會用到的.js跟圖片

在網路上 有找到解決方案
程式碼如下:

http = require("http");
var server = http.createServer(getFilename);
server.listen(80);

function sendError(errCode, errString, response)
{
response.writeHeader(errCode, {"Content-Type": "text/plain"});
response.write(errString + "\n");
response.end();
return;
}

function sendFile(err, file, response)
{
if(err) return sendError(500, err, response);
response.writeHeader(200);
response.write(file, "binary");
response.end();
}

function getFile(exists, response, localpath)
{
if(!exists) return sendError(404, '404 Not Found', response);
fs.readFile(localpath, "binary",
function(err, file){ sendFile(err, file, response);});
}

function getFilename(request, response)
{
var urlpath = url.parse(request.url).pathname;
var localpath = path.join(process.cwd(), urlpath);
console.log(localpath);
path.exists(localpath, function(result) { getFile(result, response, localpath)});
}

但是有遇到一個問題 就是因為我已經採用express模組下去寫
假使我使用以下這種方式 是OK的
app = express.createServer(getFilename);
app.listen(80);

但是因為有添加一些額外的東西 而把程式碼改成如下的形式
但發現JS都沒有載入 請問是出了什麼問題 @@? 請各位高手指點迷津

// 想把index.html跟相關的js載入
app.get('/index.html', function (req, res) {
var urlpath = url.parse(req.url).pathname;
var localpath = path.join(process.cwd(), urlpath);
console.log(localpath);
path.exists(localpath, function(result) { getFile(result, res, localpath)});
});

... 下略 ...

CaesarChi iT邦新手 3 級 ‧ 2012-05-10 02:08:21 檢舉
接應大公的方式,express static 最簡單的使用方式,

var app = express.createServer();
app.use(express.static(__dirname));
app.listen(8001);


__dirname -> 可以換成任何一個放置靜態檔案的資料夾。
希望以上對你有幫助。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

10
fillano
iT邦超人 1 級 ‧ 2012-05-05 08:10:31
最佳解答

一個一個檔案handle太麻煩了啦,請利用express.static這個middleware。

用法的話,請參考:
http://expressjs.com/guide.html#configuration
或是:
http://expressjs.com/guide.html#middleware
裡面的範例,然後自己試看看。(他沒有仔細說明,不過應該一看就懂的)簡單說,他會幫你把file system對應到route上,所以不需要一個一個檔案來handle。

我要發表回答

立即登入回答