Search code examples
angularcorsapigeeangular5

Apigee + Angular No 'Access-Control-Allow-Origin' header is present on the requested resource


Morning;

Maybe this question was asked before 100 times, but really I can not resolve it . I have this configuration in Apigee that respond to OPTIONS request.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true" name="AM-AddCors">
    <DisplayName>AM-AddCors</DisplayName>
    <Properties/>
    <Add>
        <Headers>
            <Header name="Access-Control-Allow-Origin">*</Header>
            <Header name="Access-Control-Allow-Headers">Content-Length, Content-Disposition, Origin, x-requested-with, Accept, Content-Type, Authorization</Header>
            <Header name="Access-Control-Max-Age">3628800</Header>
            <Header name="Access-Control-Allow-Methods">GET, PUT, POST, DELETE</Header>
        </Headers>
    </Add>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <AssignTo createNew="false" transport="http" type="request"/>
</AssignMessage>

In the client side I make this call with Angular (HttpClient)

public downloadS2Report(url) {
    let headers = new HttpHeaders();
    let fullurl = environment.config.fundsApi.concat(url);
    headers = headers.set("Authorization", "Bearer *****");
    return this.http.get(fullurl, {headers: headers})
      .map((response:any) => {
        if (response.status == 200) {
          var contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
          var blob = new Blob([(<any>response)._body], {type: contentType});
          return blob;
        }    
      });
  }

I can see the results in the debug view in chrome but I got the famous error with Angular "Access-Control-Allow-Origin' header is present on the requested resource". Do I miss a params in the Apigee config?

enter image description here

enter image description here

enter image description here


Solution

  • You need to respond with the relevant CORS headers on all responses, not just the OPTIONS pre-flight request. So on your GET response you also need:

    <Headers>
            <Header name="Access-Control-Allow-Origin">*</Header>
            <Header name="Access-Control-Allow-Headers">Content-Length, Content-Disposition, Origin, x-requested-with, Accept, Content-Type, Authorization</Header>
            <Header name="Access-Control-Max-Age">3628800</Header>
            <Header name="Access-Control-Allow-Methods">GET, PUT, POST, DELETE</Header>
        </Headers>