2017-05-10 32 views
1

我寫了下面的代碼:HttpServerRequest:請求被處理幾次

public static void handleRequest(HttpServerRequest request, Vertx vertx) throws FileNotFoundException { 
     if (request.method() == HttpMethod.GET) { 
      if (request.path().equals("/healthcheck")) { 
       returnResponse(request, "I'm alive!!!\n", true); 
       System.out.println("OK"); 
       return; 
      } 
      ... 

     } 
     returnResponse(request, "Not Valid Request", false); 
     System.out.println("This request cannot be handled"); 
    } 

怪異的是,一旦我得到與路徑「/健康檢查」的GET請求,我在控制檯都得到:

OK

這個請求無法處理

我希望只能得到「OK」,然後該方法必須返回。 你知道如何做到這一點嗎?

回答

2

您可能獲得多個請求,其中一個請求不是獲取請求。您可以通過插入日誌語句來監視服務器:

0

您正在嘗試處理預檢查請求。

根據MDN

不同於簡單的請求(上面討論的), 「預檢」請求第一發送一個HTTP OPTIONS請求頭 對其他域的資源,以確定是否

預檢請求 實際請求可以安全發送。跨站點請求預檢 這樣,因爲他們可能影響到用戶數據

試試這個,而不是

public static void handleRequest(HttpServerRequest request, Vertx vertx) throws FileNotFoundException { 
     if(request.method() == HttpMethod.OPTIONS) { 
      return; 
     } 

     if (request.method() == HttpMethod.GET) { 
      if (request.path().equals("/healthcheck")) { 
       returnResponse(request, "I'm alive!!!\n", true); 
       System.out.println("OK"); 
       return; 
      } 
      ... 

     } 
     returnResponse(request, "Not Valid Request", false); 
     System.out.println("This request cannot be handled"); 
    } 
1

我終於發現,我的瀏覽器發送兩個請求。 第一個請求是GET localhost:8080/healthcheck,第二個請求是GET localhost:8080/favicon。

GET localhost:8080/favicon不符合條件,代碼顯示「此請求無法處理」。