AngularでTwitterの自分のツイートのみが表示されるサンプルアプリを作ろうとした
Angularの勉強としてTwitter APIを実行して、自分のツイートだけを並べられるサンプルアプリを作成しようとした。結果としては、Twitter APIのCORS制約に引っかかってうまくいかなかった。しかし、学びが多いと思ったのでメモを残すことにする。
目的
- Angularのチュートリアルから外れて、色々試してみたかった
- HttpClientモジュールの使い方がよくわかってなかったので試してみたかった
セットアップ
基本的にはAngularチュートリアルを踏襲する形で進めていった。以下リンクは各作業の参考資料として扱う。
ng new twitter-board
Angular 日本語ドキュメンテーション - 新規プロジェクトの作成
最初にツイートのコンポーネントを作成した。
ng generate component tweets
Angular 日本語ドキュメンテーション - ヒーローエディター
次にcomponent.htmlを変更してリスト表示できるようにした。
Angular 日本語ドキュメンテーション - 選択リストを表示する
APIと疎通するためにサービスを作った。
ng generate service tweets d
Angular 日本語ドキュメンテーション - サービスの追加
Twittter APIを試した
Twitter APIの使用方法を知らないので、ドキュメントを見ながらcurlコマンドで試した。今現在は、Twitter APIを使用するために、申請とか面倒な手順が必要なのでが、幸い過去に認証のためにTwitter APIを使用したことがあり、キー情報が残っていた。したがって、それを再利用した。
JSON形式で、access_tokenが返ってくる。
curl --request 'POST' 'https://api.twitter.com/oauth2/token' --header 'Authorization: Basic [API keyとAPI secret keyを「:」で繋いでBase64エンコードした文字列]' --header 'Content-Type: application/x-www-form-urlencoded;charset=UTF-8' --data "grant_type=client_credentials" --verbose
Twitter APIのOAuthToken取得方法 - Qiita
ツイートの取得
先ほどのaccess_tokenを使用して、僕のアカウントの最新20件のツイートを取得した。
curl -H "Authorization: Bearer [access_token]" "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=ryuchan_00&count=20" | jq
Twitter APIで使うBearer Tokenの取得方法 - Qiita
GET statuses/user_timeline — Twitter Developers
これでAPIの使用方法は、おおよそ把握したことにした。
API KEYの保持を考えた
今回はサーバーサイドを実装する気は無いので、API KEYの保持方法は、 envrionment.local.ts
を作成して、コミットしないようにした。この時他の環境にも apikey
を追加しないとエラーになるので注意する。
export const environment = {
production: false,
apikey: 'hoge'
};
angular.jsonにてlocalが環境として指定された時の環境設定ファイルの読込先を書いた。
"configurations": {
...
"local": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.local.ts"
}
]
}
...
"serve": {
...
"configurations": {
...
"local": {
"browserTarget": "twitter-board:build:local"
}
これでng serveするときに -c
オプションにてlocalを指定するとローカル環境として設定した項目が読まれる。
ng serve -c local
Angularで環境変数を使用する | nobu blog
Angular 日本語ドキュメンテーション - Angularアプリのビルドとサーブ
AngularアプリケーションからTwitter APIを利用しようとした
HttpClientを使用してTwitte APIとの疎通を行った。
src/app/app.module.ts
import { HttpClientModule } from '@angular/common/http';
...
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
],
src/app/tweet.service.ts
import { HttpClient, HttpHeaders } from '@angular/common/http';
...
export class TweetService {
private twitterUrl = 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=ryuchan_00&count=20'
private httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + environment.apikey,
})
};
constructor(private http: HttpClient) { }
getTweets(): Observable<Tweet[]> {
return this.http.get<Tweet[]>(this.twitterUrl, this.httpOptions)
}
}
ブラウザで確認した結果として以下のメッセージが表示され、Twwitter APIはあなたのドメインに対しては、リソースの使用を許可していませんよとエラーメッセージが表示された。
Access to XMLHttpRequest at 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=ryuchan_00&count=20' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Angular 日本語ドキュメンテーション - HttpClient
ryuchan00/twitter-board: test angular application
次にどうするか
外部のAPIとの疎通を確認したかったのだが、使用したAPIが悪かった。とりあえずTODOリストあたりに軌道修正して触るのも良いかもしれない。