我正在使用Angular 6
。
我的应用程序需要调用多个域URL,其中一个是主服务器URL,需要添加授权头,而其他人不需要添加头。
我创建了一个Interceptor类来处理向请求添加授权头。
auth.interceptor.ts
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs';
import {AuthService} from './auth.service';
import {Injectable} from '@angular/core';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(
public Auth: AuthService
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log(this.Auth.accessToken());
console.log('inside interceptor');
request = request.clone({
setHeaders: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `${this.Auth.tokenType()} ${this.Auth.accessToken()}`
}
});
return next.handle(request);
}
}
但这是为所有网址添加标头。
如何仅将标头添加到特定网址中。
https://server.mydomain.com
只有当域os mydomain.com
没有在请求中添加标头时才应添加标头。
你可以使用location.hostname来检查域名,像这样......
if(location.hostname === 'some.domain.com') {
request = request.clone({
setHeaders: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `${this.Auth.tokenType()} ${this.Auth.accessToken()}`
}
});
} else {
request = request.clone({setHeaders: {}});
}