Reputation: 261
I am trying to implement email notification to my app using Mailgun in Angular 2. But I'm getting console error when I execute the send()
function. I don't know how to solve it, hope you can help me thanks in advance. Here is my code:
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Http, Headers, RequestOptions } from "@angular/http";
import "rxjs/Rx";
import { TabsPage } from '../tabs/tabs';
@IonicPage()
@Component({
selector: 'page-confirmorder',
templateUrl: 'confirmorder.html',
})
export class ConfirmorderPage {
recipient: string = "[email protected]";
subject: string = "FirstTesting";
message: string = "Hello, this is just a drill.";
mailgunUrl: string = "<--My Domain-->";
apiKey: string = "<--My API Key-->";
tabBarElement: any;
constructor(public http: Http, public navCtrl: NavController, public navParams: NavParams) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad ConfirmorderPage');
}
send() {
if(this.recipient && this.subject && this.message) {
let headers = new Headers(
{
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic " + this.apiKey
}
);
let options = new RequestOptions({ headers: headers });
let body = "[email protected]&to=" + this.recipient + "&subject=" + this.subject + "&text=" + this.message;
this.http.post("https://api.mailgun.net/v3/" + this.mailgunUrl + "/messages", body, options)
.map(result => result.json())
.do(result => console.log("RESULT: ", JSON.stringify(result)))
.subscribe(result => {
console.log("SENT!");
this.navCtrl.setRoot(TabsPage);
this.recipient = "";
this.subject = "";
this.message = "";
}, error => {
console.log(error);
});
}
}
}
And here is the console error:
XMLHttpRequest cannot load https://api.mailgun.net/v3/<--My Domain-->/messages. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
Upvotes: 2
Views: 618
Reputation: 5736
CORS is a chrome feature that prevents cross domain requests unless the server allows it.
In this particular case the server doesn't accept the Authorization header.
If you are doing this from your backend and not chrome this should work fine.
Do this from your backend and not angular.
Also you shouldn't put your api key/secret on the client because they become public.
Upvotes: 1