[英]How to make a Post request with “content type”: “application/x-www-form-urlencoded”?
I need to make a request to get a toke in oAuth2 authentication server. 我需要发出请求以获取oAuth2身份验证服务器中的令牌。
I can make the request in postman and get the token, can't make the same request from angular 4. 我可以在邮递员中提出请求并获得令牌,而无法从角度4中提出相同的请求。
My CORS is well-configured cause other requests are working perfectly. 我的CORS配置正确,因为其他请求运行正常。
Here are the details of HTTP request. 这是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
In angular 4, I tried this way 在角度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);
});
But this is not working. 但这是行不通的。
This is the screenshots of the postman request Headers: 这是邮递员请求标头的屏幕截图:
So how can I make this same request from angular 4? 那么如何从角度4发出相同的请求?
Here is my simple code for retrieving data of users. 这是我用于检索用户数据的简单代码。 See, headers are given as header options.
请参阅,标题作为标题选项给出。 You can view more in the 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));
}
PostRequest(url:string,data:any) { PostRequest(URL:字符串,数据:任何){
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);
}
);
});
} }
also do not forget to import import {Http, Headers,RequestOptions} from '@angular/http'; 也不要忘记从@ angular / http导入import {Http,Headers,RequestOptions};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.