简体   繁体   中英

Sending an HTTP request with headers in Angular2

I am trying to build an app that connects to the twitter api. To accomplish this, I need to send a http get request with a set of headers using Angular2.

Note, the below curl requests is successful (assuming the correct keys are in place).

This is what I tried, the only issue is, with the below implementation, I am an unable to pass in the necessary headers.

Was wondering if anybody has encountered this and has any suggestions on how to resolve?

Thanks in advance

constructor(private _http: Http) {

}

getTwitterResponse() {
         return this._http.get('https://api.twitter.com/1.1/statuses/home_timeline.json')
            .map(res => res.text);
}

Curl Request Sample w/ Headers (w/ auth keys removed)

 curl --get 'https://api.twitter.com/1.1/statuses/home_timeline.json' --header 'Authorization: OAuth oauth_consumer_key="123456", oauth_nonce="123456", oauth_signature="f%123456%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1475158916", oauth_token="123456", oauth_version="1.0"' --verbose

You add headers to your request like this:

import { Headers, RequestOptions } from '@angular/http';    

getTwitterResponse() {

let headers = new Headers({ "Content-Type": "application/json" });
let options = new RequestOptions({ headers: headers });
let url = 'https://api.twitter.com/1.1/statuses/home_timeline.json';

     return this._http.get(url, options).map(res => res.text);
}

Explanation of what's happening here: request get of Http have the following signature:

get(url: string, options?: RequestOptionsArgs)

Second argument is optional and it's type is RequestOptionsArgs which is an interface used to construct RequestOptions , which means you can pass RequestOptions to get as a second argument. RequestOptionsArgs is an interface with following attributes:

export interface RequestOptionsArgs {
    url?: string;
    method?: string | RequestMethod;
    search?: string | URLSearchParams;
    headers?: Headers;
    body?: any;
    withCredentials?: boolean;
    responseType?: ResponseContentType;
}

All attributes are optional and that's why we can pass only headers to our options . You can change Content-Type with anything you want and you can add more than 1 header:

headers: Headers = new Headers({
    'First header': 'First value',
    'Second header': 'Second value',
    'Third header': 'Third value',
    'Fourth header': 'Fourth value'
});

You can read more about everything I just blabbed about on the following links:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM