问题
getHeroes (): Observable<Heros[]> {
return this.http.get(this.heroesUrl)
.map(this.extractData)
.catch(this.handleError);
}
Where I add the headers and how? looking for a simple example.
回答1:
You can define a Headers object with a dictionary of HTTP key/value pairs, and then pass it in as an argument to http.get()
and http.post()
like this:
const headerDict = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Headers': 'Content-Type',
}
const requestOptions = {
headers: new Headers(headerDict),
};
return this.http.get(this.heroesUrl, requestOptions)
Or, if it's a POST request:
const data = JSON.stringify(heroData);
return this.http.post(this.heroesUrl, data, requestOptions);
回答2:
if someone facing issue of CORS not working in mobile browser or mobile applications, you can set ALLOWED_HOSTS = ["your host ip"] in backend servers where your rest api exists, here your host ip is external ip to access ionic , like External: http://192.168.1.120:8100
After that in ionic type script make post or get using IP of backened server
in my case i used django rest framwork and i started server as:- python manage.py runserver 192.168.1.120:8000
and used this ip in ionic get and post calls of rest api
来源:https://stackoverflow.com/questions/42352854/how-i-add-headers-to-http-get-or-http-post-in-typescript-and-angular-2