-3

I have a project with Angular Framework and Asp.net Core.

In my ConfigureServices I have bellow code:

services.AddCors(options =>
            {
                options.AddPolicy(
                    "CorsPolicy",
                    builder => builder
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());
            });

And un Configure as follow:

 app.UseCors("CorsPolicy");
 app.UseMvc();

And after that added EnbaleCors attribute in BaseApiController

[EnableCors("CorsPolicy")]
public class BaseApiController : Controller

In Angular added follow:

return this.http
        .post(url, body, { headers: headers, withCredentials: true })
        .map((response: Response) => {
            return response as any;
        })

When I run the application I have 2 requests in Network, One of them Request Method: OPTIONS with Status Code: 204 No Content and other in my request.

Where is my problem?

Thanks for taking the time and share your ideas

Saeid Mirzaei
  • 950
  • 2
  • 18
  • 48

1 Answers1

1

It's not a problem and there is no need to worry.

For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request HTTP resources from the same origin the application was loaded from, unless the response from the other origin includes the right CORS headers.

The OPTIONS request is merely a security check for safe network calls between cross origins. Hence, when you make such a request, the client will send an OPTIONS request to same address to ensure that it is safe to send the original request(GET/POST).

MonkeyScript
  • 4,776
  • 1
  • 11
  • 28
  • @arcreezy Thanks, Can I disable or hide this OPTIONS request in production? – Saeid Mirzaei Feb 16 '19 at 07:19
  • @SaeidMirzaei I don't think you can't disable client from sending CORS request if client and server are in different domains. There might be a workaround by changing **Content-Type** of your requests to `application/x-www-form-urlencoded` or `multipart/form-data` or `text/plain` but i wouldn't encourage it. – MonkeyScript Feb 16 '19 at 07:45
  • I don't have any different domains, I have two subdomains like 'api.my-doamin.com' and 'client.my-doamin.com'. Is it ok in this situation? – Saeid Mirzaei Feb 16 '19 at 08:31
  • 1
    @SaeidMirzaei What i meant with different domains are your client and server and not the URLs. As I told, it won't cause any issue whatsoever. – MonkeyScript Feb 16 '19 at 08:56