0

I have follow this tutorial of angular 7 to make a CRUD functions. I publish the project into my IIS but I am having an error (Image)

Access to XMLHttpRequest at 'http://192.168.120.178:2030/Api/Employee/UpdateEmployeeDetails/' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I tried to add the header in Update Code to allow the CORS but its the same.

The error also applies to other functions (Save, Delete)

Angular Code

updateEmployee(employee: Employee): Observable<Employee> {
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Access-Control-Allow-Credentials': "true",
    'Access-Control-Allow-Headers': 'Content-Type',
    'Access-Control-Allow-Methods': 'GET',
    'Access-Control-Allow-Origin': '*'
  })
};
return this.http.put<Employee>(this.url + '/UpdateEmployeeDetails/',
  employee, httpOptions);
}

API Code

   [HttpPut]
        [Route("UpdateEmployeeDetails")]
        public IHttpActionResult PutEmaployeeMaster(EmployeeDetail employee)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            try
            {
                EmployeeDetail objEmp = new EmployeeDetail();
                objEmp = objEntity.EmployeeDetails.Find(employee.EmpId);
                if (objEmp != null)
                {
                    objEmp.EmpName = employee.EmpName;
                    objEmp.Address = employee.Address;
                    objEmp.EmailId = employee.EmailId;
                    objEmp.DateOfBirth = employee.DateOfBirth;
                    objEmp.Gender = employee.Gender;
                    objEmp.PinCode = employee.PinCode;

                }
                int i = this.objEntity.SaveChanges();

            }
            catch (Exception)
            {
                throw;
            }
            return Ok(employee);
        }

But If im running my project using a localhost API its okay. But in publish (IIS) im getting the CORS error. I spent one whole day already but unfortunately I didn't see a solution to my problem.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Ano Ni Mos
  • 23
  • 3
  • 1
    You're setting the `Access-Control-Allow-*` header in the request (Angular) but they should be set of the response (IIS), what you need is probably something [like this](https://support.microsoft.com/en-us/help/954002/how-to-add-a-custom-http-response-header-to-a-web-site-that-is-hosted/) – Mendy Aug 14 '19 at 03:07
  • @Mendy what should i put in Header name and Value? – Ano Ni Mos Aug 14 '19 at 03:20
  • The names would be `Access-Control-Allow-Origin`, `Access-Control-Allow-Methods`, etc..., and the values would be `*`, `GET`, etc... . Got it? – Mendy Aug 14 '19 at 04:56
  • @Mendy I added it as instruction. And now I'm having a new error. `response to preflight request doesn't pass access control check` – Ano Ni Mos Aug 14 '19 at 05:34
  • Possible duplicate of [XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header](https://stackoverflow.com/questions/35553500/xmlhttprequest-cannot-load-xxx-no-access-control-allow-origin-header) – Quentin Aug 14 '19 at 09:34
  • @Mendy link is broken :( – Steve Smith Mar 28 '22 at 15:22
  • Updated link https://learn.microsoft.com/en-us/troubleshoot/developer/webapps/iis/development/add-http-response-header-web-site – Mendy Mar 29 '22 at 16:13

2 Answers2

1

TL;DR: You actually have the CORS headers in the wrong direction.

The API (server side) needs to be the one returning the CORS headers as a way of signaling to the browser that you expected whatever domain the Angular UI is being served on (client side) to call your API.

See this article from Mozilla about CORS

If you think about it, it doesn't make sense for the client side / browser to set these CORS headers, because the client side can easily be compromised by a bad actor (such as chrome plugin, foreign javascript, etc.), and if the client side was in charge of these CORS headers, it would be really easy to make them be what a hacker wants them to be. Instead, they need to come from the server side - hinted at by the Access-Control-* prefix. It's the server's way of whitelisting domains it expects the front end to access it from.

Another way to think about it would be that I couldn't create a website that directly hit Facebook's API's if they have their CORS headers restricted to only allow *.facebook.com because I don't own that domain. CORS are also a protection layer to prevent bad actors from being able to use your server side APIs and spoof your front end to capture people's data.

Bwvolleyball
  • 2,593
  • 2
  • 19
  • 31
0

if it is .net core go in Startup.cs and serve both back-end and front-end with https and enable CORS

public void ConfigureServices(IServiceCollection services)
{
...
      services.AddCors();
...
}


   public void Configure(IApplicationBuilder app)
   {
    ...
      app.UseCors(builder =>
            builder.WithOrigins("YOUR_FRONTEND_URL")
                   .AllowAnyHeader()
                   .AllowAnyMethod()
                   .AllowCredentials());
    ...
    }

Source

Web API 2 (Prior Core)

Install-Package Microsoft.AspNet.WebApi.Cors

App_Start\WebApiConfig.cs

public static void Register(HttpConfiguration config)

{

            var cors = new EnableCorsAttribute(

                origins: "YOUR_FRONTEND_URL",

                headers: "*",

                methods: "*");

            config.EnableCors(cors);
            ...
}

More Information

SGalea
  • 712
  • 9
  • 18