Abort spray request when aborted from reactjs

95 Views Asked by At

I am new to scala and spray. I am able to abort request from reactJS. And it shows in network tab of browser console that the request is cancelled. But from scala it is not aborting. In logs i can see api is getting hitted. For Rest API I am using spray in scala. Here is my reactJS code:

    new Promise((accept, _reject) => {
    fetch("/api/complete", {
      method: "post",
      signal: controller.signal,
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify(requestBody)
    })

Ans here is my scala code:

pathPrefix("complete") {
    post {
        entity(as[completeRequest]) { completeRequest =>
            complete {
                    completeService()
            }
        }
    }
}

def completeService(): Future[HttpResponse] = {

    val pipeline: HttpRequest => Future[HttpResponse] = sendReceive ~> unmarshal[HttpResponse]
    val response: Future[HttpResponse] = pipeline(Post(someremoteUrl.concat("complete"), botCompleteRequest)
      ~> addHeader("demo", "test"))
    response
}

So how to abort this complete request when it is aborted from reactJS/promise

1

There are 1 best solutions below

6
Moritz On

Short answer: You don't.

It does matter if it is React (or Angular, or jQuery) on the client-side and it does not matter what is on the server-side (scala, PHP, .NET).

What matters is the HTTP between client and server.

In HTTP you can't "catch" a request that is already sent. The abort function in js/browser pretty much only means that it will ignore the response. Once a request is sent and is in the network, it will hit the server, and the server will process it. The server never gets notified that the client canceled the request.

This question and the answer cover the topic quite well: https://softwareengineering.stackexchange.com/questions/362187/can-a-caller-abort-an-execution-of-code-invoked-by-http-request