簡體   English   中英

node.js 在服務 index.html 文件后不執行任何代碼

[英]node.js does not execute any code after serving the index.html file

我試圖在用戶訪問 index.html 頁面時為其分配 sessionId。 但是,在對“/”的 GET 請求和 index.html 作為響應發送后不會執行任何代碼。

以下是有問題的代碼

app.get('/', (req, res) => {
  // A unique identifier for the given session
  const sessionId = uuid.v4();
  if(req.session.uuid)
  {

  } else {
    req.session.uuid = sessionId;
  }
  console.log("Session ID : " + req.session.uuid);
  res.sendFile(path.join(__dirname+'/public/index.html'));
})

顯式發送 index.html 文件也是一種好習慣,因為即使刪除 res.sendFile() 調用也會發送它。

我的猜測是您在此之前有一個express.static()中間件處理程序,它為index.html提供服務,因此此代碼永遠不會運行。

express.static()看到對/的請求,並且還會在您指向express.static()的目錄中看到index.html文件,則它會自動發送index.html

您可以通過三個選項來解決此問題:

  1. 你可以在你的express.static()中間件之前移動這個處理程序,這樣它就可以在服務/時首先被破解。
  2. 您可以將index.html移動到express.static()未查看的其他目錄。
  3. 您可以將選項傳遞給express.static(path, {index: false})以告訴它不要提供index.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM