2016-07-07 8 views
0

我正在學習節點js/express並有一個快速問題。在express中爲get方法使用多個不同的html文件是不好的。例如,對於每個get方法,我打開一個不同的html文件。使用許多不同的HTML頁面快遞

app.get('/', function(req, res){ 
    var html = fs.readFileSync('index2.html'); 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.end(html); 
}); 


app.get('/continuous', function(req, res){ 
    var html = fs.readFileSync('index6.html'); 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.end(html); 
}); 

app.get('/output', function(req, res){ 
    var html = fs.readFileSync('index4.html'); 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.end(html); 
}); 
+0

這很好,但你爲什麼在這裏使用'fs'?只是'res.sendFile(PATH)'會做... – Rayon

+0

哦好吧謝謝,fs就是我在教程中找到的,但會使用res.sendFile – Baner

回答

0

可以使用res.sendFile,使這個過程更簡單:

app.get('/game', function (req, res) { 
    res.sendFile('/game.html', { 
     root: path.join(__dirname, '/public') 
    }); 
}); 
1

Althought不總是有用,蛞蝓是相當巨大的。

app.get('/:page', function(req, res) { 
    res.sendFile(__dirname + '/' + req.params + ".html"); 
}); 

localhost/some-page的請求會從同一目錄返回文件some-page.html

請注意不要在敏感數據的同一目錄中執行此操作。

相關問題