I'm very confused by an error we are getting with a new Angular6 application. We have an existing API written in ASP.NET Core 2 and we have been consuming this API without issue from a chrome extension written in Typescript which posts data like so:
let login: any = {
username: options.userName,
password: options.password
};
let body: string = JSON.stringify(login);
return fetch(`${environment.jwtApiUrl}/api/token`,
{
method: "POST",
headers: {
'Accept': 'application/json',
"Content-Type": "application/json"
},
body: body
});
We are now consuming the exact same API from our Ionic 4 Angular application like so:
export class AuthenticationService {
constructor(
private http: HttpClient,
private storage: Storage) { }
public isLoggedIn(): boolean {
return this.storage.get("token") != null;
}
public async login(username: string, password: string): Promise<boolean> {
let login: any = {
username: username,
password: password
};
let body: string = JSON.stringify(login);
var result = await this.http.post<any>(`${environment.jwtApiUrl}/api/token`, body).toPromise();
if (result && result.token) {
this.storage.set("token", result.token);
return true;
};
return false;
}
logout() {
// remove user from local storage to log user out
this.storage.remove('token');
}
}
Within the angular application we are using an HttpInterceptor:
export class JwtInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with jwt token if available
console.log("JwtInterceptor");
let token = JSON.parse(localStorage.getItem('token'));
if (token) {
request = request.clone({
setHeaders: {
"Authorization": `Bearer ${token}`
}
});
}
if (!request.headers.has('Content-Type')) {
request = request.clone({ headers: request.headers.set('Content-Type', 'application/json') });
}
console.log(request);
return next.handle(request);
}
}
In Angular the POST becomes an OPTIONS request and we get a 404 not found and:
Failed to load https://oururl/api/token: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
Why do we get this just from Angular and not from the chrome extension which is also doing cross domain calls and is there anyway to work around this other than enabling cors on the API?