I am trying to make a simple email form for one of my websites that allows people to contact me. This site is using angular 4, and mailgun as the mail service. In my mail service file I have this method that sends the message, but I am getting a Bad Request error saying from is not present.
public sendMail(){
let url = 'https://api.mailgun.net/v3/XXXXXXXXXXXX.mailgun.org/messages';
let headers: Headers = new Headers();
headers.append('Authorization','Basic '+ btoa('api:key-XXXXXXXXXXXXXXXXXXX'));
headers.append("Content-Type", "application/x-www-form-urlencoded");
let opts: RequestOptions = new RequestOptions();
opts.headers = headers;
this.http.post(url,
{
from: '"Mailgun Sandbox" <postmaster#XXXXXXXXXX.mailgun.org>',
to: "Test <test#gmail.com>",
subject: 'Hello ',
text: 'Congratulations, you just sent an email with Mailgun! You are truly awesome!'
},
opts
).subscribe(
success => {
console.log("SUCCESS -> " + JSON.stringify(success));
}, error => {
console.log("ERROR -> " + JSON.stringify(error));
}
);
}
I am having a hard time understanding why from is showing up not as present when I send the request. Any help is great.
import { Injectable } from '#angular/core';
import { HttpHeaders, HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class PostService {
constructor(private http: HttpClient) {
}
sendMail() {
const headers = new HttpHeaders({
'enctype': 'multipart/form-data',
'Authorization': 'Basic ' + btoa('api:xxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxxx-xxxxxx')
});
const formData = new FormData();
formData.append('from', 'Mailgun Sandbox <postmaster#sandboxxxxxxxxxxxxxx.mailgun.org>');
formData.append('to', 'xxxxxxxxxxxxxx.com');
formData.append('subject', 'Hello');
formData.append('text', 'This is cool !');
this.http
.post(
'https://api.mailgun.net/v3/sandboxxxxxxxxxxxxxxxxxxxxxxxxxxb.mailgun.org/messages',
formData,
{ headers }
).subscribe(
res => { console.log('res : ', res); },
err => { console.log('err : ', err); }
);
}
}
Related
I've post method at my angular service say AuthService.ts like this
#Injectable({
providedIn: 'root'
})
export class AuthService {
...
...
login(username: string, password: string) {
let headers = new Headers(); //1
headers.append('username', username); //2
let options = {
headers: headers
}; //3
return this.http.post < any > (`${environment.authBaseUrl}`, {
username,
password
}, options) //4
.pipe(map(user => {
if (user && user.token) {
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
}
return user;
}));
}
}
My purpose is to add the username at the POST request header. Cause there in the API it is expecting that a username will be found at the request header. With the help of this post in StackOverflow, I'm trying to add the header (from comment 1 to 4). I'm getting the below error message -
TS2345:
Argument of type '{ headers: Headers; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
Types of property 'headers' are incompatible.
Type 'Headers' is not assignable to type 'HttpHeaders | { [header: string]: string | string[]; }'.
Type 'Headers' is not assignable to type '{ [header: string]: string | string[]; }'.
Index signature is missing in type 'Headers'.
If I remove the option from the post method then everything works fine.
Can anyone help me with this?
Thanks in advance
Use HttpHeaders instead of Headers,
import { HttpHeaders } from '#angular/common/http';
let options = {
headers: new HttpHeaders({ 'username': username })
}
Consider using HttpHeaders.
For example:
(I just put application/json content-type header for example purpose).
import { HttpHeaders } from '#angular/common/http';
[...]
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json', 'username': username)
};
[...]
return this.http.post<any>(`${environment.authBaseUrl}`, { username, password }, httpOptions) //4
.pipe(map(user => {
if (user && user.token) {
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
}
return user;
}));
Currently I am trying to POST a name, email and message from an angular frontend to a php script running in the same nginx server which then runs phpmailer to send an email containing the name, email and message. Here is the code so far:
import { Component, OnInit } from '#angular/core';
import { Email } from './email';
import {ContactService} from './contact.service';
import {HttpClient, HttpHeaders} from '#angular/common/http';
import {NgForm} from '#angular/forms';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})
};
const email = new Email('', '', '');
#Component({
selector: 'app-contact',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.css'],
providers: [ContactService]
})
export class ContactComponent implements OnInit {
email = new Email('', '', '');
constructor(private http: HttpClient) { }
sendEmail(form: NgForm) {
const value = form.value;
const senderName = value.name;
const senderEmail = value.email;
const senderMessage = value.message;
this.sendMail(senderName, senderEmail, senderMessage);
}
sendMail(senderName, senderEmail, senderMessage) {
console.log(senderName + ' ' + senderEmail + ' ' + senderMessage);
this.http.post('https://ruffstuffcostumes.tk/assets/scripts/email.php',
{
name: senderName,
email: senderEmail,
message: senderMessage,
},
httpOptions
)
.subscribe(
(val) => {
console.log('POST call successful value returned in body',
val);
},
response => {
console.log('POST call in error', response);
},
() => {
console.log('The POST observable is now completed.');
});
}
ngOnInit() {
}
}
When I ran the POST request through postman to check it, it ran perfectly well and sent out the email containing the required elements, however when I execute a query with this script, even though the console.log(senderName + ' ' + senderEmail + ' ' + senderMessage) does show the values, it doesn't seem to post them in the body at all, and all I get back is the fact that even though a mail was sent, it was sent without any of those values in the body of the email.
Could it be cross-origin problems (and if so what would be the best way to get around that?), or am I just doing some stupid mistake?
Just for completeness. I solved the problem by switching to sending JSON data and parsing it on the php side
I'm new to angular2. In 1.* everything was fine with interceptors, just add them: and you have everywhere your headers, and you can handle your requests, when token became invalid...
In angular2 i'm using RxJs.
So i get my token:
getToken(login: string, pwd: string): Observable<boolean> {
let bodyParams = {
grant_type: 'password',
client_id: 'admin',
scope: AppConst.CLIENT_SCOPE,
username: login,
password: pwd
};
let params = new URLSearchParams();
for (let key in bodyParams) {
params.set(key, bodyParams[key])
}
let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
let options = new RequestOptions({headers: headers});
return this.http.post(AppConst.IDENTITY_BASE_URI + '/connect/token', params.toString(), options)
.map((response: Response) => {
let data = response.json();
if (data) {
this.data = data;
localStorage.setItem('auth', JSON.stringify({
access_token: data.access_token,
refresh_token: data.refresh_token
}));
return true;
} else {
return false;
}
});
}
and then how can i use this token in every request? i don't want to set .header in every request. It's a bad practice.
And then: for example when i do any request, and get 401-error, how can i intercept, and get a new token, and then resume all requests, like it was in angular 1?
i tried to use JWT from here jwt, but it doesn't meet my requirements, btw in first angular i was using Restangular - and everything was fine there (also with manual on tokens:https://github.com/mgonto/restangular#seterrorinterceptor)
You can either extend the default http service and use the extended version, or you could create a method that gets some parameters (if necessary) and return a RequestOptions objects to pass default http service.
Option 1
You can create a service:
#Injectable()
export class HttpUtils {
constructor(private _cookieService: CookieService) { }
public optionsWithAuth(method: RequestMethod, searchParams?: URLSearchParams): RequestOptionsArgs {
let headers = new Headers();
let token = 'fancyToken';
if (token) {
headers.append('Auth', token);
}
return this.options(method, searchParams, headers);
}
public options(method: RequestMethod, searchParams?: URLSearchParams, header?: Headers): RequestOptionsArgs {
let headers = header || new Headers();
if (!headers.has('Content-Type')) {
headers.append('Content-Type', 'application/json');
}
let options = new RequestOptions({headers: headers});
if (method === RequestMethod.Get || method === RequestMethod.Delete) {
options.body = '';
}
if (searchParams) {
options.params = searchParams;
}
return options;
}
public handleError(error: Response) {
return (res: Response) => {
if (res.status === 401) {
// do something
}
return Observable.throw(res);
};
}
}
Usage example:
this._http
.get('/api/customers', this._httpUtils.optionsWithAuth(RequestMethod.Get))
.map(res => <Customer[]>res.json())
.catch(err => this._httpUtils.handleError(err));
This example is using cookies to store and access the token. You could use a parameter as well.
Option 2
Second option is to extend http service, for example like this:
import { Injectable } from '#angular/core';
import { Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Headers } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
#Injectable()
export class MyHttp extends Http {
constructor (backend: XHRBackend, options: RequestOptions) {
let token = 'fancyToken';
options.headers.set('Auth', token);
super(backend, options);
}
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
let token = 'fancyToken';
if (typeof url === 'string') {
if (!options) {
options = {headers: new Headers()};
}
options.headers.append('Auth', token);
} else {
url.headers.append('Auth', token);
}
return super.request(url, options).catch(this.handleError(this));
}
private handleError (self: MyHttp) {
return (res: Response) => {
if (res.status === 401) {
// do something
}
return Observable.throw(res);
};
}
}
And in your #NgModule:
#NgModule({
// other stuff ...
providers: [
{
provide: MyHttp,
useFactory: (backend: XHRBackend, options: RequestOptions) => {
return new MyHttp(backend, options);
},
deps: [XHRBackend, RequestOptions]
}
]
// a little bit more other stuff ...
})
Usage:
#Injectable()
class CustomerService {
constructor(private _http: MyHttp) {
}
query(): Observable<Customer[]> {
return this._http
.get('/api/customers')
.map(res => <Customer[]>res.json())
.catch(err => console.log('error', err));
}
}
Extra:
If you want to use refresh token to obtain a new token you can do something like this:
private handleError (self: MyHttp, url?: string|Request, options?: RequestOptionsArgs) {
return (res: Response) => {
if (res.status === 401 || res.status === 403) {
let refreshToken:string = 'fancyRefreshToken';
let body:any = JSON.stringify({refreshToken: refreshToken});
return super.post('/api/token/refresh', body)
.map(res => {
// set new token
})
.catch(err => Observable.throw(err))
.subscribe(res => this.request(url, options), err => Observable.throw(err));
}
return Observable.throw(res);
};
}
To be honest, I haven't tested this, but it could provide you at least a starting point.
We solved the issue with extension of AuthHttp. We added a method a on AuthHttp to set a new header dynamically like that (X-RoleId is a custom header)
declare module 'angular2-jwt' {
interface AuthHttp {
setRoleId(config: {});
}
}
AuthHttp.prototype.setRoleId = function (roleId) {
let jsThis = <any>(this);
jsThis.config.globalHeaders = [
{'Content-Type': 'application/json'},
{'X-RoleId': roleId}
];
};
I am trying the gmail apis. I've done the auth. Now I want to create a draft. But I am getting this error
{ error:
I20161220-15:53:43.486(4)? { errors: [Object],
I20161220-15:53:43.487(4)? code: 400,
I20161220-15:53:43.488(4)? message: 'Media type \'application/octet-stream\' is not supported. Valid media types: [message/rfc822]' } } }
Gmail api require base64 string with rfc822 standard. I am not sure of any good way to convert a string to rfc822. How do I do that?
I am using meteor for my app and here is my code.
import { Meteor } from 'meteor/meteor'
import { HTTP } from 'meteor/http'
Meteor.startup(() => {
// Meteor.call('createDraft')
Meteor.methods({
'createDraft': function () {
console.log(this.userId)
const user = Meteor.users.findOne(this.userId)
const email = user.services.google.email
console.log(email)
const token = user.services.google.accessToken
const dataObject = {
message: {
raw: CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse('dddd'))
},
headers: {
Authorization: `Bearer ${token}`
}
}
HTTP.post(`https://www.googleapis.com/upload/gmail/v1/users/${email}/drafts`, dataObject, (error, result) => {
if (error) {
console.log('err', error)
}
if (result) {
console.log('res', result)
}
})
}
})
})
Base64 encode the message and replace all + with -, replace all / with _, and remove the trailing = to make it URL-safe:
const rawMessage = btoa(
"From: sender#gmail.com\r\n" +
"To: receiver#gmail.com\r\n" +
"Subject: Subject Text\r\n\r\n" +
"The message text goes here"
).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
const dataObject = {
message: {
raw: rawMessage
},
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
}
};
I just needed to send content type as message/rfc822. Here is the working code. Note that the raw message has something wrong in ts because the draft that is created has empty content. But the draft itself is created successfully.
import { Meteor } from 'meteor/meteor'
import { HTTP } from 'meteor/http'
Meteor.startup(() => {
// Meteor.call('createDraft')
Meteor.methods({
'createDraft': function () {
console.log(this.userId)
// CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse('dddd'))
const user = Meteor.users.findOne(this.userId)
const email = user.services.google.email
console.log(email)
const token = user.services.google.accessToken
const rawMessage = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(
'From: sender#gmail.com\r\n' +
'To: receiver#gmail.com\r\n' +
'Subject: Subject Text\r\n\r\n' +
'The message text goes here'
)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
const dataObject = {
message: {
raw: rawMessage
},
headers: {
'Content-Type': 'message/rfc822',
Authorization: `Bearer ${token}`
}
}
HTTP.post(`https://www.googleapis.com/upload/gmail/v1/users/${email}/drafts`, dataObject, (error, result) => {
if (error) {
console.log('err', error)
}
if (result) {
console.log('res', result)
}
})
}
})
})
I am using ionic 2 / angular 2.
I need to do a http request, but before I have to get a token using Ionic Storage.
I created a class ApiRequest for that
import {Http, Headers, RequestOptions} from '#angular/http';
import {Injectable} from '#angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Storage } from '#ionic/storage';
#Injectable()
export class ApiRequest {
access_token: string;
constructor(private http: Http, public storage: Storage) {
this.storage.get('access_token').then( (value:any) => {
this.access_token = value;
});
}
get(url) {
let headers = new Headers({
// 'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.access_token,
'X-Requested-With': 'XMLHttpRequest'
});
let options = new RequestOptions({ headers: headers });
return this.http.get(url, options)
.map(res => res.json());
}
}
Then I can call like that
apiRequest.get(this.URL)
.subscribe(
data => {
this.element= data;
},
err => {
console.log(JSON.stringify(err));
});
My problem is, this.storage.get is asynchronous, http.get is asynchronous too, and I have to return http.get because I want to call subscribe outside the function.
In this case http.get is called before this.acess token received the value.
How Can I organize my code in that scenario?
This might work (not tried myself):
#Injectable()
export class ApiRequest {
access_token: string;
constructor(private http: Http, public storage: Storage) {
this.storagePromise = this.storage.get('access_token').then( (value:any) => {
this.access_token = value;
});
}
get(url) {
let headers = new Headers({
// 'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.access_token,
'X-Requested-With': 'XMLHttpRequest'
});
let options = new RequestOptions({ headers: headers });
return this.storagePromise.then(
return token => this.http.get(url, options)
.map(res => res.json());
);
}
}
apiRequest.get(this.URL)
.then(observable =>
observable.subscribe(
data => {
this.element= data;
},
err => {
console.log(JSON.stringify(err));
}
);