简体   繁体   中英

How do i get HTTP status code 200 instead of 202 from an ajax call

The below code always receives a HTTP '202 Accepted' status code: 在此处输入图像描述

When I try the same API using postman I get 200 OK": 在此处输入图像描述

function ExportStatus() {
  function ExportStatusAjax() {
    $.ajax({
      type: "GET",
      url: "https://api.powerbi.com/v1.0/myorg/groups/" + groupId + "/reports/" + reportId + "/exports/" + exportId + "",
      headers: {
        "Authorization": "Bearer " + accessToken
      },
      success: function(data, textStatus, jqXHR) {
        if (jqXHR.status == 200) {
          GetExportFile()
        } else {
          ExportStatusAjax()
        }
      },
      error: function(err) {
        alert(error)
      }
    });
  }

  ExportStatusAjax()
}

You have a recursion that will never end. ExportStatusAjax() calls itself in 2 places at least. Remove it from your code at all. And don' t pay to much attention to the status codes if there are not 400x or 500x. As soon as it returns to success you are ready to continue.

I am not familiar with Power BI, so I can't say for sure, but judging by your code and the API status codes, this looks like a case of an asynchronous API. What that means is, instead of the traditional model in HTTP where the client submits a request and gets the response back (this is a 200, aka OK ), a client submits an HTTP request and the response is a placeholder to tell you that the real response is not ready yet.

202 is called Accepted and I believe that in this situation it is being used to indicate your request has been accepted into a queue. The idea being that, if you keep retrying, eventually it will be done and you'll get the real response, which comes with a status code of 200 . Reports, analytics, or other sorts of computationally expensive workloads often follow this pattern.

This approach is a common pattern. If that is in fact what is happening here, then your code is probably correct and seeing the response flip between 202 and 200 is normal.

With that said, your approach is constantly hammering the server. As soon as it gets back a 202 , it immediately retries, which adds load to the remote system, which theoretically may actually slow it down.

I suggest putting in a timer to delay the retries, maybe every 3 seconds or 5 seconds or so. The setTimeout function can help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM