I need to make a request to get a toke in oAuth2 authentication server.
I can make the request in postman and get the token, can't make the same request from angular 4.
My CORS is well-configured cause other requests are working perfectly.
Here are the details of HTTP request.
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
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?
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) {
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';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.