TypeScript - Discord OAuth と CORS を使った Angular インターセプター
私はDiscordでのOAuth2ログインを設定しようとしています。OAuthコードを取得するURLを 'environment.ts' の環境変数として設定したので、問題はURLのスペルミスではありません。
hrefアンカーリンクは問題なく動作しますが、サービスメソッドを呼び出し、(私の理解では)インターセプターを組み合わせると、毎回このエラーが発生します(省略された認可URL)。
Access to XMLHttpRequest at 'https://discord.com/oauth2/authorize.....' (redirected from 'https://discord.com/api/oauth2/authorize?....') from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
インターセプターコード:
import {Injectable} from '@angular/core';
import{
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEvent
} from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class CustomInterceptor implements HttpInterceptor {
constructor() {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("testing...");
request = request.clone({
withCredentials: true
});
return next.handle(request);
}
}
HTMLページ
<div>
<button class="btn btn-primary btn-center" (click)="login()"> Login With Discord </button>
</div>
<div>
<a href={{login_url}}>Login2</a>
</div>
対応するTSファイル:
import { Component, OnInit } from '@angular/core';
import { OauthService } from '../../services/oauth/oauth.service';
import {DISCORD_LOGIN_URL} from '../../../environments/environment';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private oauthService: OauthService) { }
login_url = DISCORD_LOGIN_URL;
ngOnInit(): void {
}
public login():void {
this.oauthService.login().subscribe(
data => console.log(data)
);
}
}
ボタンが押されたときにメソッドが呼び出されるサービスファイル:
import { Injectable } from '@angular/core';
// import {Response } from '@angular/http';
import {HttpClient, HttpErrorResponse} from '@angular/common/http';
import { throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import {DISCORD_LOGIN_URL} from '../../../environments/environment';
import {CLIENT_ID} from '../../../environments/environment';
import {CLIENT_SECRET} from '../../../environments/environment';
import {REDIRECT_URI} from '../../../environments/environment';
import {SCOPE} from '../../../environments/environment';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class OauthService {
clientId: string;
clientSecret: string;
login_url: string;
scope: string;
redirect_uri: string;
token: string;
constructor(private http: HttpClient) {
this.clientId = CLIENT_ID;
this.clientSecret = CLIENT_SECRET;
this.redirect_uri = REDIRECT_URI+ '/main';
this.scope = SCOPE;
this.login_url = DISCORD_LOGIN_URL;
}
public requestCore(): Observable<any> {
return this.http
.get(this.login_url)
}
public login(): Observable<any> {
return this.http
.get(this.login_url);
}
handleError(error: HttpErrorResponse) {
let errorMessage = 'Unknown error!';
if (error.error instanceof ErrorEvent) {
errorMessage = `Error: ${error.error.message}`;
} else {
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
window.alert(errorMessage);
return throwError(errorMessage);
}
}
以前に同様の問題があったかどうか調べてみましたが、見つかりませんでした(おそらく見落としている可能性もあります)。ほとんどの投稿ではサーバー側でクロスオリジンを許可するように書かれていますが、アンカーのhrefが機能しているので、それが問題だとは思えません。
よろしくお願いします!
追伸:最終的にはこのAngularプロジェクトを公開で使う予定なので、ローカルのブラウザにChromeプラグインをインストールしたり設定を無効にしたりすることは考えていません。
編集 1 - ボタンをクリックするとネットワーク呼び出しが2回発生しており、最初の呼び出しはCORSを通過してステータス302で完了し、次の呼び出しが失敗していると私は信じています。
追記2 - server.jsファイルにこのコードを使ってExpressサーバーで設定を試みましたが、同じエラーが出続けています;
app.use(express.static('./dist/De-Bot'),
function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
