0

I'm trying to make HTTP POST request to consume Mailchimp API (From Angular7 code) but i'm getting this response:

Access to XMLHttpRequest at 'https://us12.api.mailchimp.com/3.0/lists/ddddddd/members' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

From REST client i'm able to make insert in Mailchimp without having this CROS issue

enter image description here

export class MyService {
  
  constructor(public httpRequestsService: HttpRequestsService) { }

  private async getHttpHeader() {
    const rheaders = new HttpHeaders({
      'Content-Type': 'application/json' , 
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
      'Access-Control-Allow-Headers':'X-Requested-With',
      'Authorization': 'apikey ' + MailchimpSettings.API_KEY
    });
    return { headers: rheaders };
  }

  public async AddNewMember(email: string, language = 'en', status = , mergeFields?: any) {
    var url = MailchimpSettings.URL;

    var body = {
      "email_address": email,
      "status": MailchimpSettings.SUBSCRIBED_STATUS,
      "language": language
    };
    
    var httpOptions = await this.getHttpHeader();
    var _body = JSON.stringify(body);

    var result = await this.post(url, _body, httpOptions);
    
  }
  
  public async post(url: string, body: string | {} = {}, requestHeaders?: any): Promise<Response> {
     
     return this.http.post(url, body, requestHeaders).toPromise()
       .then((res: any) => {
         return res;
       })
       .catch((err) => {
         return this.handleErrorPromise(err);
       });
   }
}

Anyone who can help me with right HTTP headers (or any required change) to reproduce exactly REST client behavior and be able to make a successful POST.

Thanks for your help

Heykel
  • 11
  • 1

1 Answers1

0

Unfortunately, the answer is you can't. Mailchimp does not support CORS because that would require passing API credentials, and that is not secure.

The option is to make requests from another server like you mentioned from the REST client or make a custom signup form that will use more restricted API call.

Or use jsonp request for mailchimp form clients.

See this

ahmetovicajdin
  • 344
  • 4
  • 14