簡體   English   中英

HTTP 發布請求已取消

[英]HTTP Post Request canceled

我有一個 javascript 服務,可將國家/地區添加到 postgresql 數據庫的列表中。 一切正常,但是當我在 chrome 開發工具中打開網絡選項卡時,發布請求未完成,並且在狀態列中顯示已取消。

地位

當我查看一般的 header 時,沒有執行任何發布請求

標題

將請求放在一起的 Javascript 代碼如下所示:

function toevoegenLand(){
  document.querySelector("#toevoegen").addEventListener("click", function (){
  var formData = new FormData(document.querySelector("#toevoegform"));
  var encData = new URLSearchParams(formData.entries());
  
  var fetchoptions = {method: 'POST', body:encData, headers: {'Authorization' : 'Bearer ' + window.sessionStorage.getItem("sessionToken")}};
  
  fetch("restservices/countries/", fetchoptions)
  .then(response => response.json())
  .then(function(myJson){ console.log(myJson); });
  
  location.reload();
  
})

請求在 WorldResource.Java 中處理

@POST
@RolesAllowed("user")
@Produces("application/json")
public Response addCountry(@Context SecurityContext sc, 
                           @FormParam("addCode")String c,
                           @FormParam("addCountry")String nm,
                           @FormParam("addCapital") String h,
                           @FormParam("addRegion") String r,
                           @FormParam("addOpp") double o,
                           @FormParam("addPop") int i,
                           @FormParam("addGov")String g,
                           @FormParam("addCon")String cn){
    
    Country newLand = service.saveLand(c, nm, h, r, o, i, g, cn);
    System.out.println(newLand);
    return Response.ok(newLand).build();
}

HTML 形式沒什么特別的

<form id="toevoegform">
            Code:<input type="text" id="addCode" name="addCode"><br>
            Land:<input type="text" id="addCountry" name="addCountry"><br>
            Hoofdstad:<input type="text" id="addCapital" name="addCapital"><br>
            Regio:<input type="text" id="addRegion" name="addRegion"><br>
            Oppvervlakte:<input type="text" id="addOpp" name="addOpp"><br>
            Inwoners:<input type="text" id="addPop" name="addPop"><br>
            Overheid:<input type="text" id="addGov" name="addGov"><br>
            Continent:<input type="text" id="addCon" name="addCon"><br>
            <button type="button" id= "toevoegen">Toevoegen</button>
            </form>

為什么請求被取消? 或者我怎么能弄清楚這個?

fetch("restservices/countries/", fetchoptions) .then(response => { response.json(); location.reload(); } ).then(function(myJson){ console.log(myJson); });

這可能是因為您在請求完成之前重新加載了頁面。 改為這樣做:

fetch("restservices/countries/", fetchoptions)
    .then(response => response.json())
    .then(function(myJson){
        // Here you are sure that your request has been done 
        location.reload();
    });

由於您正在處理 Promise (代碼異步運行),因此您無法確定它將在以下說明之前執行。

希望它有所幫助。

暫無
暫無

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

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