2016-02-14 78 views
1

我是新來的Node.js和Express.js及其路由。它的設置都正確,除了下面的代碼外,它都可以工作。ExpressJS sendFile()不能發送URL GET參數

我嘗試下面的代碼:

app.get("/game/*", function(req, res) { 
    res.sendFile(__dirname + "/public/game.html?gameId=" + /\/([^\/]+$)/.exec(req.url)[1]); 
}); 

的目標是將所有請求與/game/{gameId}(其中gameId是一些數字)/public/game.html?gameId={gameId}

它正確地獲取請求與/game/,從URL獲取gameId參數,並嘗試sendFile()它。然而,sendFile()不工作,他說:

web.1 | Error: ENOENT, stat '/opt/lampp/htdocs/papei/public/game/32'

我搜索這個錯誤,我想它有沒有被發現的文件做。問題是,/public/game.html存在。如果我刪除sendFile()中的部分,那麼它就可以工作。但我想sendFile()正在尋找一個確切的網址,並沒有找到它。

有沒有辦法使用ExpressJS發送URL GET參數?

回答

1

我認爲問題在於sendFile試圖按照您的想法找到完全匹配(您的查詢參數中斷)。

你可以使用express-static服務於HTML頁面,然後根據需要像這樣重定向到它:

app.get("/game/:gameid", function(req, res) { 
    // Not ideal, as it uses two requests 
    res.redirect('/game.html?gameId=' + req.params.gameid) 
}); 

或者你可以把HTML模板內,使其在應對如:

app.get("/game/:gameid", function(req, res) { 
    // Render the 'game' template and pass in the gameid to the template 
    res.render('game', {gameid: req.params.gameid}) 
}); 

無論採用哪種方式,您都不需要使用捕獲所有路由和正則表達式來獲取查詢參數,請參見快速文檔中的req.paramsreq.query

希望這會有所幫助。

+0

我正在嘗試重定向,但它不起作用。我不確定你將如何製作模板 - 你能否提供相關文檔?謝謝。 –

+0

另外,「express-static」是什麼意思?它與我目前使用的代碼有什麼不同? –

+1

如果您嘗試使用重定向,請確保您的快速靜態中間件位於重定向路由的下方。 [Here](http://expressjs.com/en/guide/using-template-engines.html)是解釋模板引擎的文檔,[here](http://expressjs.com/en/starter/static-files .html)是提供靜態文件(又名'express-static')的文檔。 –