我正在为SalesForce api创建访问令牌,当我通过http.post()发送请求时,我收到错误,如Bad Requests 400。 这是我的代码:
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;
}
但下面的代码完美无缺:
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;
}
但是我想运行代码的第一部分。不管是什么问题!
答案 0 :(得分:1)
尝试在不使用JSON.stringify(this.body);
的情况下运行您的第一个代码
将this.body直接发送到post方法。
答案 1 :(得分:1)
JSON.stringify不会将params对象转换为正确的格式。您需要使用自定义功能。见the working plunker。它返回invalid_client_id
,更改凭据。
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("&");
}