app.get('/',function(req,res,next){
app.use(express.static(html file);
next();
});
app.get('/:someText',function(req,res){
var x = req.params.someText;
res.send(x);
});
我得到兩個輸出,但沒有得到該文件的CSS的CSS。如何在node.js中獲取/和/:someText?
app.get('/',function(req,res,next){
app.use(express.static(html file);
next();
});
app.get('/:someText',function(req,res){
var x = req.params.someText;
res.send(x);
});
我得到兩個輸出,但沒有得到該文件的CSS的CSS。如何在node.js中獲取/和/:someText?
正如我從代碼中可以看出你缺少發送的get /。
app.get('/',function(req,res,next){
//something
//in here add res.send() and all OK.
});
請檢查以瞭解接下來的內容。
你使用express.static
的方式是不正確的。你不應該把它傳遞給一個文件來返回,那就是sendFile
。 express.static
用於提供整個目錄,應在get
處理程序外調用。
例如,這將在您的URL的根目錄中提供一個名爲public
的目錄。未找到文件的任何請求將通過中間件/路由器鏈傳遞到下一個處理:
app.use(express.static(path.join(__dirname, 'public')));
重要的本應出現在您的通話app.get
,app.post
等之前,而不是一個處理器中。
所以,如果你有一個在public/myfile.html
的文件,將在http://localhost:3000/myfile.html
服務,我假設你的服務器在localhost:3000
。如果您想爲網址添加一部分路徑,例如http://localhost:3000/stat/myfile.html
這將是:
app.use('/stat', express.static(path.join(__dirname, 'public')));
如果你想成爲一個單一的文件,那麼你可以使用sendFile
,有點像這樣:
app.get('/myfile.html', function(req, res) {
res.sendFile(path.join(__dirname, '/myfile.html'));
});
注意,這是挑出一個特定的文件,因此任何像CSS這樣的資源需要分開處理。如果HTML,CSS等都在同一個文件夾中,那麼使用express.static
來代替整個目錄是有意義的。
還值得注意的是,express.static
有一個名爲index
的設置,默認情況下提供一個名爲index.html
的文件,如果請求進入'/'。
進一步閱讀: