使用 HttpClient 在单击 post 请求时触发两个调用

Two calls triggering on click of post request using HttpClient

在内部代码中添加 headers 后发生重复调用。找到图片以查看通话发生两次。

auth-interceptor.ts

export class AuthInterceptor 实现 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

第一次调用由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.

另请参阅有用的 article 了解更多信息。

这种类型的请求被称为Preflighted 请求,它对应于调用者和基于 HTTP headers 的 Web 应用程序之间的协商。

它包括两个阶段:

  1. 浏览器执行与目标请求相同URL的OPTIONS请求,以检查其是否具有执行该请求的权限。此 OPTIONS 请求 returns headers 确定可以为 URL 做什么。

  2. 如果权限匹配,浏览器执行请求。

Reference here.