我遇到了一个我无法解决的问题。我正在使用一个Ionic + angular App,它使用HTTPClient发出请求。使用'ionic serve'命令运行它可以正常运行并且请求成功,但是当我想使用模拟器运行它时,它会给我这个错误
Failed to load resource: net::ERR_CONNECTION_REFUSED
HttpErrorResponseerror: ProgressEventheaders: HttpHeadersmessage: "Http failure response for (unknown url): 0 Unknown Error"name: "HttpErrorResponse"ok: falsestatus: 0statusText: "Unknown Error"url: null__proto__: HttpResponseBase
我读过可能发生了与CORS相关的事情但是,我为此设置了标题并且没有发生。
这是我每次发出请求时执行的拦截器代码
@Injectable()
export class HttpInjectableHeader implements HttpInterceptor {
private authService: UserData;
constructor(private injector: Injector){}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.authService = this.injector.get(UserData); // get it here within intercept
if (req.params.has('noAuth')){
const modified = req.clone({setHeaders: {
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE',
'Access-Control-Allow-Headers': 'Origin, Content-Type,Accept, X-Auth-Token ,App-Auth,X-XSRF-TOKEN,Authorization'
}});
return next.handle(modified);
}
else{
return Observable.fromPromise(this.authService.getAccessToken())
.switchMap(token => {
const modified = req.clone({setHeaders: {Authorization: `Bearer ${token}`,'Access-Control-Allow-Origin':'*'}});
console.log(req);
return next.handle(modified);
});
}
}
}
以下是'ionic info'命令的输出
cli packages: (/usr/local/lib/node_modules)
@ionic/cli-utils : 1.19.1
ionic (Ionic CLI) : 3.19.1
global packages:
cordova (Cordova CLI) : 8.0.0
local packages:
@ionic/app-scripts : 3.1.0
Cordova Platforms : android 7.0.0 browser 5.0.3 ios 4.5.4
Ionic Framework : ionic-angular 3.9.2
System:
Node : v6.12.3
npm : 5.6.0
OS : macOS High Sierra
Environment Variables:
ANDROID_HOME : not set
Misc:
backend : pro
在我的服务器端,我有这个配置
# NelmioCors Configuration
nelmio_cors:
paths:
'^/api/':
allow_origin: ['*']
allow_headers: ['*']
allow_methods: ['POST', 'PUT', 'GET', 'DELETE','OPTIONS']
max_age: 3600
'^/oauth/v2/token':
allow_origin: ['*']
allow_headers: ['*']
allow_methods: ['POST', 'PUT', 'GET', 'DELETE','OPTIONS']
max_age: 3600