Angular 9: Uncaught DOMException: Blocked a frame with origin - javascript

I just developed sign in authentication for an Angular app and I went to test it. Sign up works just fine. Then I sign out and attempt to sign in and the header does not update as expected, instead I get this error in console:
Uncaught DOMException: Blocked a frame with origin
"chrome-extension://hdokiejnpimakedhajhdlcegeplioahd" from accessing a
cross-origin frame.
at e [as constructor] (chrome-extension://hdokiejnpimakedhajhdlcegeplioahd/lpfulllib.js:1:1441712)
at new e (chrome-extension://hdokiejnpimakedhajhdlcegeplioahd/lpfulllib.js:1:1444920)
at chrome-extension://hdokiejnpimakedhajhdlcegeplioahd/lpfulllib.js:1:1461728
But I am not authenticated because I get:
{authenticated: false, username: null}
authenticated: false
username: null
Even though the GET request itself went through successfully, but there is a problem there, because it's not supposed to be a GET but a POST request. Why does it think it's a GET request?
My signin() method inside my auth service clearly shows it's a post request:
signin(credentials: SigninCredentials) {
return this.http.post(this.rootUrl + "/auth/signin", credentials).pipe(
tap(() => {
this.signedin$.next(true);
})
);
}
Here is my auth http interceptor code:
import { Injectable } from "#angular/core";
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpEventType,
} from "#angular/common/http";
import { Observable } from "rxjs";
#Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
// Modify or log the outgoing request
const modifiedReq = req.clone({
withCredentials: true,
});
return next.handle(modifiedReq);
}
}
Now I do not think the issue is in my AuthHttpInterceptor, I believe the problem is in AuthService:
import { Injectable } from "#angular/core";
import { HttpClient } from "#angular/common/http";
import { BehaviorSubject } from "rxjs";
import { tap } from "rxjs/operators";
interface UsernameAvailableResponse {
available: boolean;
}
interface SignupCredentials {
username: string;
password: string;
passwordConfirmation: string;
}
interface SignupResponse {
username: string;
}
interface SignedinResponse {
authenticated: boolean;
username: string;
}
interface SigninCredentials {
username: string;
password: string;
}
#Injectable({
providedIn: "root",
})
export class AuthService {
rootUrl = "https://api.my-email.com";
signedin$ = new BehaviorSubject(false);
constructor(private http: HttpClient) {}
usernameAvailable(username: string) {
return this.http.post<UsernameAvailableResponse>(
this.rootUrl + "/auth/username",
{
username,
}
);
}
signup(credentials: SignupCredentials) {
return this.http
.post<SignupResponse>(this.rootUrl + "/auth/signup", credentials)
.pipe(
tap(() => {
this.signedin$.next(true);
})
);
}
checkAuth() {
return this.http
.get<SignedinResponse>(this.rootUrl + "/auth/signedin")
.pipe(
tap(({ authenticated }) => {
this.signedin$.next(authenticated);
})
);
}
signout() {
return this.http.post(this.rootUrl + "/auth/signout", {}).pipe(
tap(() => {
this.signedin$.next(false);
})
);
}
signin(credentials: SigninCredentials) {
return this.http.post(this.rootUrl + "/auth/signin", credentials).pipe(
tap(() => {
this.signedin$.next(true);
})
);
}
}

I see you have no HttpHeaders. While I do not see your backend configuration, I suspect the mis configuration causes your exception.
You can update your Angular interpector to something like this:
import {
HttpEvent,
HttpHandler,
HttpHeaders,
HttpInterceptor,
HttpRequest,
} from '#angular/common/http'
import { Injectable } from '#angular/core'
import { Observable } from 'rxjs'
#Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// const token = localStorage.getItem('access_token')
// const userToken = localStorage.getItem('id_token')
if (token) {
const authRequest = req.clone({
setHeaders: {
'Content-Type': 'application/json',
// Authorization: `Bearer ${token}`,
// userID: `${userToken}`,
},
})
return next.handle(authRequest)
} else {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
})
const cloned = req.clone({
headers,
})
return next.handle(cloned)
}
}
}
Also make sure that your backend is aligned and headers such as Access-Control-Allow-Origin configured to true

That is caused by LastPass extension. Deactivate it and the error will disappear.

Related

How to send Time zone Offset in request header in Angular?

I would like to send Time zone Offset in request header. But I have not find any way to do it.
My code is given below:
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '#angular/common/http';
import { Observable } from 'rxjs';
import { Injectable } from '#angular/core';
import { SessionProvider } from './session.provider';
#Injectable({ providedIn: 'root' })
export class TokenInterceptor implements HttpInterceptor {
constructor(private provider: SessionProvider) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const update = addHeaders(req, this.provider.session);
const request = req.clone(update);
return next.handle(request);
}
}
function addHeaders(req: HttpRequest<any>, session: any): any {
let headers = req.headers;
if (session?.stationId) {
headers = headers.set('wid', session.stationId);
}
if (session?.accessToken) {
headers = headers.set('Authorization', 'Bearer ' + session.accessToken);
}
return { headers };
}
I want to add Time zone Offset in addHeaders function. If someone knows how it can be done them please share your thoughts
It can be done as follow:
function addHeaders(req: HttpRequest<any>, session: any): any {
let headers = req.headers;
if (session?.stationId) {
headers = headers.set('wid', session.stationId);
}
if (session?.accessToken) {
headers = headers.set('Authorization', 'Bearer ' + session.accessToken);
}
headers = headers.set('tz-offset', getTimeZoneOffset());
return { headers };
}
function getTimeZoneOffset(): string {
const tzOffset = new Date().toTimeString().match(/([\+-]\d{4})/)[0];
return [tzOffset.slice(0, 3), ':', tzOffset.slice(3)].join('');
}

How can I take the data in this service from an HTTP get call?

I have a little issue from an Angular app to get a code from my own server.
I´ve built up a little Spotify App for learning more about Angular 10 and have a little backend that I only use for get the Bearer code to call the Spotify API, but the fact is that in my Angular front I can´t save the code.
Tis is my service call code to the back:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { map } from 'rxjs/operators';
import { environment } from '../../environments/environment';
#Injectable({
providedIn: 'root'
})
export class SpotifyService {
token: any;
constructor(private http: HttpClient) {
console.log('Spotify service ready');
this.getAccesToken().subscribe(data => this.token = data['access_token']);
}
getAccesToken(){
return this.http.get(environment.server + `${environment.client_id}/${environment.client_secret}`)
.pipe(
map(res => res)
);
}
getQuery(query: any){
const headers = new HttpHeaders({
'Authorization': `Bearer ${this.token}`
});
const url = `https://api.spotify.com/v1/${query}`;
return this.http.get(url, {headers});
}
I´ve checked the recibed data and I get the request perfectly, but can´t save the data of the suscriber into a variable.
Thanks in advance!
Assuming your component code looks like below, you can make some adjustments and try it.
export class SomeComponent implements OnInit {
spotifyData;
user;
token;
constructor(private spotifyService: SpotifyService, private http: HttpClient) { }
ngOnInit() {
this.user = JSON.parse(localStorage.getItem('user'));
console.log(this.user);
this.token = this.user.token;
this.getSpotifyData();
}
getSpotifyData() {
this.spotifyService.getQuery(this.user, { headers: new HttpHeaders().set('Authorization', 'Bearer ' + this.token) }).subscribe(res => {
console.log(res);
if (res) {
spotifyData = res;
} else {
spotifyData = []
}
});
}

Http interceptors are not working angular 7

I have upgraded my angular app from 4 to latest version 7. After so many errors I finally got it to work but now there is one problem: services are not working, like it is not giving any error in the console but not working as well.
I think the problem is with my Http interceptor and the factory in which I am missing something.
Can someone tell me what the issue is, exactly?
Http interceptor
export class InterceptedHttp extends HttpClient
constructor(
backend: HttpBackend,
private store: Store<any>,
private spinnerService: SpinnerService
) {
super(backend);
}
request( url: string | HttpRequest<any>, options?: any): Observable<any> {
this.showLoader();
return this.tryCatch(super.request(this.getRequestOptionArgs(options)))
}
get(url: string, options?: any): Observable<any> {
url = this.updateUrl(url);
return this.tryCatch(super.get(url));
}
post(url: string, body: string, options?: any): Observable<any> {
url = this.updateUrl(url);
return this.tryCatch(
super.post(url, body)
);
}
put(url: string, body: string, options?: any): Observable<any> {
url = this.updateUrl(url);
return this.tryCatch(
super.put(url, body)
);
}
delete(url: string, options?: any): Observable<any> {
url = this.updateUrl(url);
return this.tryCatch(super.delete(url));
}
patch(url: string, body: any, options?: any): Observable<any> {
url = this.updateUrl(url);
return this.tryCatch(
super.patch(url, body)
);
}
private updateUrl(req: string) {
return environment.origin + req;
}
private getRequestOptionArgs(options?: any): any {
if (options.headers == null) {
options.headers = new HttpHeaders();
}
options.headers.append('Content-Type', 'application/json');
options.headers.append(
'Authorization',
` Bearer ${sessionStorage.AccessToken}`
);
return options;
}
private tryCatch(obs: Observable<any>) {
return obs.pipe(catchError((error: HttpResponse<any>, caught) => {
if (error.status === 401 && sessionStorage.AccessToken) {
sessionStorage.clear();
this.store.dispatch({type: 'LOGOUT'});
}
this.hideLoader();
return observableThrowError(error);
}));
}
Http factory
export function httpFactory(xhrBackend: HttpXhrBackend,
store: Store<any>, spinnerService: SpinnerService): HttpClient {
return new InterceptedHttp(xhrBackend, store, spinnerService);
}
provider in app module
{
provide: HttpClient,
useFactory: httpFactory,
deps: [HttpXhrBackend, Store, SpinnerService]
},
Whenever I login it just starts loading, nothing else, no error or anything and when I comment out the provider in the app module it says "404 not found error".
Any help?
Thanks
Can't comment on how you did interceptors in Angular 4. But since 4.3 HttpInterceptor was introduced so here is an example on how you do http interceptors in Angular 7:
#Injectable()
export class ApiInterceptor implements HttpInterceptor {
constructor(private someService: SomeService) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return this.someService.getBaseUrl().pipe(
mergeMap(baseUrl => {
const apiRequest = data
? request.clone({ url: `${baseUrl}${request.url}` })
: request;
return next.handle(apiRequest);
})
);
}
}
Here is an example of a intercept that does nothing but returning the request unchanged:
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(request);
});
How to provide it:
import { HTTP_INTERCEPTORS } from '#angular/common/http';
// ...
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: ApiInterceptor, multi: true }
]
You can inspect the request object to check the request type (POST, GET) and do what ever you want with it.
This might be obvious (or not) but HttpInterceptor only works if your requests are made with the HttpClient introduced in Angular 4.3. If your requests are made by other http client (the older client from HttpModule, native code or other library) it will not work, AFAIK.
Also if you try to lazy load the interceptor it will not be straightforward (not even sure if its possible), so first try to get it to work like this.

Type Promise<void> is not assignable to type Promise<customType[]>

I am new to angularJs2. I have created following service:
import { Injectable, OnInit } from '#angular/core';
import { customType } from '../models/currentJobs';
import { Headers, Http } from '#angular/http';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class JobService implements OnInit {
constructor(private http: Http) { }
ngOnInit(): void {
this.getCurrentJobs();
}
private headers: Headers = new Headers({ 'Content-Type': 'application/json' });
private ordersUrl: string = 'http://localhost:35032/api/order/';
public orders: customType[];
getCurrentJobs(): Promise<customType[]> {
var jobs = this.http.get(this.ordersUrl)
.toPromise()
.then(response => {
this.orders = response.json() as customType[];
})
.catch(this.handleError);
return jobs;//this line throws error
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
Following are my Typescript compile configuration of Vs2017
When I compile the code using visual studio 2017 I get following error
**TS2322 Build:Type 'Promise<void>' is not assignable to type 'Promise<customType[]>'.**
Help me to fix this error.
You are not returning anything inside your then which makes jobs be of type Promise<void>. Return the array inside then:
getCurrentJobs(): Promise<customType[]> {
var jobs = this.http.get(this.ordersUrl)
.toPromise()
.then(response => {
this.orders = response.json() as customType[];
return this.orders;
})
.catch(this.handleError);
return jobs;
}
See the chaining behaviour of promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then#Chaining
I've added the 'catch' operator, and swapped your interface import for an interface definition in the code (as I don't obviously have access to yours). I can't really test this without the rest of your project code, but it looks right to me and doesn't throw any errors in VSC.
import { Injectable, OnInit } from '#angular/core';
import { Headers, Http } from '#angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/catch';
export interface customType{
}
#Injectable()
export class JobService implements OnInit {
constructor(private http: Http) { }
private jobs: Promise<customType[]>;
ngOnInit(): void {
this.jobs = this.getCurrentJobs();
}
private headers: Headers = new Headers({ 'Content-Type': 'application/json' });
private ordersUrl: string = 'http://localhost:35032/api/order/';
public orders: customType[];
getCurrentJobs(): Promise<customType[]> {
return this.http.get(this.ordersUrl)
.map(response => response.json())
.catch(this.handleError)
.toPromise();
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}

Iterate through an array of objects Angular 2 component

Can anyone help what I am doing incorrect, anything missing?
I am getting undefined for --'this.ack.length'
this._activeChannelService.requestChannelChange(this.selectedchannel.channelName)
.subscribe(
ack => {
this.ack= ack;
console.log(" test: ", this.ack.length);
},
err => {
console.log(err);
});enter code here
ack is of time
ack:Iack[];
Iack has two field of type string. result and message
I need to iterate through array of Iack[] to get the result and message
if message=success then call the another service
service
requestChannelChange (name: string): Observable<Iack[]> {
alert('in servicerequestChannelChange');
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
let postchannelname = "channelName=" + name;
let requestt = new IRequest(name);
console.log(JSON.stringify(requestt));
return this._http.post(this._activateChangeUrl, JSON.stringify(requestt),{ headers: headers })
//.map(this.extractData)
.map((res:Response) => res.json() as Iack[])
.do(data => console.log("All: " + JSON.stringify(data)))
.catch(this.handleError);
}
You can use observable in your TS service:
import { Injectable } from '#angular/core';
import { IPost } from './IPost';
import { Http, Response, RequestOptions, Headers } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
#Injectable()
export class PostServices {
private _webApiBaseUrl = "http://localhost:62806/v1/Posts"
private _http : Http;
constructor(http : Http){
this._http = http;
}
getAll(): Observable<IPost[]> {
        return this._http.get(this._webApiBaseUrl + '/all', this.getHeaders())
.map((response: Response) => response.json())
.do(data => console.log(`All Data: \n ${ JSON.stringify(data) }`))
.catch(this.handleError);
    }
private handleError(error: Response){
console.error(error);
return Observable.throw(error.json().error || 'Server Error');
}
private getHeaders()
{
let headers = new Headers();
headers.append("Authorization", "");
headers.append("Content-Type", "application/json");
return new RequestOptions({ headers: headers });
}
}
Usage in your TS class:
import { Component, OnInit } from '#angular/core';
import { IPost } from './IPost';
import { PostServices } from './posts.service';
#Component({
selector: 'app-posts',
templateUrl: './posts.component.html',
styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {
posts: IPost[];
errorMessage: string;
private _postService: PostServices;
constructor(postService: PostServices) {
this._postService = postService;
}
ngOnInit() {
this._postService.getAll()
.subscribe(
data => {this.posts = data; console.log("data.length: " + data.length)}, // here
error => this.errorMessage = <any>error
);
}
}
enter code here is executed before this.ack= ack; is executed
This is a function
ack => {
this.ack= ack;
console.log(" test: ", this.ack.length);
}
that you pass to subscribe(...) and the observable calls it when the data arrives which can take a looong time when it's a call to a server.
enter code here is executed immediately.
You'll have to check for success within the service subscription. An observable is an asynchronous call, so any calls you want to make regarding the data in that async call must be made within it to remain a safe call.
So, make your seconds service call, within the subscription.

Categories