如何使用"内容类型制作帖子请求":" application / x-www-form-urlencoded"?

时间:2017-10-23 18:08:31

标签: node.js angular oauth-2.0 http-post

我需要在oAuth2身份验证服务器中发出请求。

我可以在邮递员中提出请求并获得令牌,不能从角度4发出相同的请求。

我的CORS配置良好,因为其他请求工作正常。

以下是HTTP请求的详细信息。

POST /oauth/token HTTP/1.1
Host: localhost:8080
Authorization: Basic YXBwbGljYXRpb246c2VjcmV0
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: 9f9582e9-fe73-499f-d7f7-82498a974e39

grant_type=password&username=pedroetb&password=password

在角度4中,我试过这种方式

let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    headers.append("Authorization","Basic YXBwbGljYXRpb246c2VjcmV0");

    var obtainTokenUrl = 'http://localhost:8080/oauth/token';

    this._http.post(obtainTokenUrl + "?grant_type=password&username=pedroetb&password=password", null, {headers: headers}).subscribe(response => {
      console.log(response);
    });

但这不起作用。

这是邮递员请求的屏幕截图 头: enter image description here

身体: enter image description here

那么如何从角度4发出同样的请求呢?

2 个答案:

答案 0 :(得分:0)

这是我检索用户数据的简单代码。请参阅,标题以标题选项的形式给出。您可以在docs

中查看更多内容
createUser(user: User): Observable<User> {
    const submittedUser = JSON.stringify(user); // user is form-submitted data object
    const headers = new Headers ({ 'Content-Type': 'application/json' });
    const options = new RequestOptions({headers: headers});
    return this.http.post(baseURL + 'user/create', submittedUser, options)
      .map((response: Response) =>  {this.processHttpmsgService.extractData(response);})
      .catch(error=> Observable.throw(error));
  }

Docs for HeaderOptions

答案 1 :(得分:0)

PostRequest(url:string,data:any){

var headers = new Headers();

let req = JSON.stringify(data);

 this.onRequest("request: " + url + "data: " + req);

headers.append ("content-Type","application/json");
headers.append("charset","utf-8;");
headers.append("Access-Control-Allow-Origin", "*");
var token = localStorage.getItem('token');
headers.append("Authorization","Bearer "+ token);

 let options = new RequestOptions({ headers: headers });
console.log(options);

  // don't have the data yet
 return new Promise(resolve => {

   this.http.post(url,req,options)
   .map(res => res.json())
   .subscribe(data => {
     resolve(data);

     this.onSuccess(data);
  }
  ,error => {
 this.onError(error);
  }
  );
});

}

也不要忘记导入 从&#39; @ angular / http&#39;;

导入{Http,Headers,RequestOptions}