Estoy creando un token de acceso para la API de SalesForce y cuando envío solicitudes a través de http.post() recibo un error como Bad Requests 400. Aquí está mi código:
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; }Pero el siguiente código funciona perfectamente:
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; }Pero quiero ejecutar la primera parte del código. ¡No sepas cuál es el problema!
intente ejecutar su primer código sin usar JSON.stringify(this.body); envíe this.body directamente al método de publicación.
JSON.stringify no convierte el objeto params al formato correcto. Necesita usar la función personalizada. Ver el plunker de trabajo . Devuelve invalid_client_id , cambie las credenciales.
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("&"); }