Two calls triggering on click of post request using HttpClient [duplicate]

时光怂恿深爱的人放手 提交于 2019-12-29 08:24:14

问题


After adding headers inside code duplicate call is happening. find the image to see the call happening twice.

auth-interceptor.ts

export class AuthInterceptor implements HttpInterceptor {

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const clonedRequest = req.clone({
        headers: req.headers.set('X-CustomAuthHeader', 'some-auth-token')
    });

    console.log("new headers", clonedRequest.headers.keys());

    return next.handle(clonedRequest);
}

}

Please fine calls log image here..

call log 1

call log 2


回答1:


This type of request is called Preflighted requests that corresponds to a negotiation between the caller and the Web application based on HTTP headers.

It consists of two phases:

  1. The browser executes an OPTIONS request with the same URL as the target request to check that it has the rights to execute the request. This OPTIONS request returns headers that identify what is possible to do for the URL.

  2. If rights match, the browser executes the request.

Reference here.




回答2:


The first call is triggered by Cross-Origin Resource Sharing (CORS)

It sends first an OPTION request to check if the domain, from which the request is sent, is the same as the one from the server.

Notice that if you add authentication to the request using the Authentication header, simple requests automatically become preflighted ones.

See also helpful article for more information.



来源:https://stackoverflow.com/questions/47033278/two-calls-triggering-on-click-of-post-request-using-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!