1

I am trying to do get request from angular 5 as below:

public showHeatMap(){
        console.log("in showHeatMap")
        let headers = new Headers();
        headers.append('Access-Control-Allow-Origin' , '*');
/*      
        headers: new HttpHeaders({
            'Content-Type':  'image/png',
            'Access-Control-Allow-Origin': '*'
        }) */
        this.http.get(this.showHeatMapURL,{headers: headers}).toPromise().then((res)=>{
            console.log("reading response....")
            console.log(res);
      });
    }

but it gives me error as "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

Naresh Pawar
  • 179
  • 2
  • 3
  • 15
  • 7
    You should set the header in backend, **not** frontend, so this has really nothing to do with angular :) – AT82 Oct 09 '18 at 11:56
  • 1
    @AJT_82 ok thanks for quick response. – Naresh Pawar Oct 09 '18 at 11:59
  • :) No problem :) – AT82 Oct 09 '18 at 12:02
  • Possible duplicate: https://stackoverflow.com/questions/50607264/how-to-enable-access-control-allow-origin-for-angular-5-nodejs; https://stackoverflow.com/questions/45527935/getting-no-access-control-allow-origin-header-is-present-on-the-requested-res; https://stackoverflow.com/questions/41683195/access-control-allow-origin-issue-in-angular-2 – Learning Oct 09 '18 at 12:09
  • 1
    I handle it in backend using "corsheaders" and it solved my problem. Thanks again @AJT_82. – Naresh Pawar Oct 09 '18 at 12:30

3 Answers3

1

You need to enable CORS in your Web Api. The easier and preferred way to enable CORS globally is to add the following into web.config

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>
</system.webServer>
Z.ain
  • 11
  • 2
0

If you use Spring as your backend server. You can use @CrossOrigin annotation to solve it.

Just like:

@CrossOrigin
@RestController
public class DemoController {
    @GetMapping("/getHeatMap") 
    public Object getHeatMap() {
    ...
    }
}

This annotaion is also useful to single function.

Xu Duan
  • 1
  • 1
-1

If you are using Spring Boot as your backend then the solution which is provided to add

@CrossOrigin just above your Controller class is working in my case.