I am creating access token for SalesForce api and when I send requests through http.post() I am getting error like Bad Requests 400. Here is my code:
getToken():Observable<any[]>{
this.body={grant_type:'password',client_id:'3MVG9d8..57qfn8zsI8Du1zalkfIOVSz0qw_6Way_SrP6fP1apM3Pges9bhahYwdg.',client_secret:'5035130443686',username:'user@demo.com',password:'blabla'};
this.body2=JSON.stringify(this.body);
let headers = new Headers({"Content-Type": "application/json"});
let options = new RequestOptions({ headers});
this.authorization = this.http.post("https://demo-dev-ed.my.salesforce.com/services/oauth2/token",this.body2,options)
.map((res:any) => res.json());
return this.authorization;
}
But the below code works perfectly:
getToken():Observable<any[]>{
var body="grant_type=password&client_id=3MVG9d8..z.Sz0qw_6Way_SrP6fP1apM3Pges9bhahYwdg.&client_secret=50351305443686&username=user@demo.com&password=blabla";
let headers = new Headers({"Content-Type": "application/x-www-form-urlencoded"});
let options = new RequestOptions({ headers});
this.authorization = this.http.post("https://demo-dev-ed.my.salesforce.com/services/oauth2/token",this.body,options)
.map((res:any) => res.json());
return this.authorization;
}
But I want to run the first part of code.Don't what is the issue!
try to run your first code without using JSON.stringify(this.body);
send this.body directly to the post method.
JSON.stringify doesn't convert params object to the right format. You need to use custom function. See the working plunker. It returns invalid_client_id, change credentials.
getToken():Observable<any[]>{
const body = {grant_type:'password',client_id:'3MVG9d8..57qfn8zsI8Du1zalkfIOVSz0qw_6Way_SrP6fP1apM3Pges9bhahYwdg.',client_secret:'5035130443686',username:'user@demo.com',password:'blabla'};
const bodyStr = this.buildString(body);
let headers = new Headers({"Content-Type": "application/x-www-form-urlencoded"});
this.authorization = this.http.post("https://demo-dev-ed.my.salesforce.com/services/oauth2/token", bodyStr, { headers: headers })
.map((res:any) => res.json());
return this.authorization;
}
buildString(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}