Angular encountering HTTP failure while parsing with ngrok

Currently, I am developing an application to monitor drink prices during a stock market event. Initially, everything was functioning correctly while testing on localhost via Chrome. However, I decided to experiment with port forwarding for both the NestJS backend and Angular frontend using ngrok.

After troubleshooting, I discovered that the issue lies within the Angular frontend as my requests are not reaching ngrok.

Within the frontend, the DrinksService is responsible for requesting all drinks from the backend.

export class DrinksService {
  constructor(private http: HttpClient, private localService: LocalService) { }

  private url: string = 'https://7a4c-81-241-237-61.ngrok-free.app/drinks';
  drinks: Drink[] = [];

  getDrinks(): Observable<Drink[]> {
    console.log('Attempting to fetch drinks from the backend');
    return this.http.get<Drink[]>(this.url);
  }

...continued code snippet...
}

To further elaborate, when accessing the URL in my browser or Postman, I receive a correct JSON response (displayed below).

[{"name":"Pintje","alcohol":true,...}]

However, upon trying to execute the getDrinks() method, I encounter an Http error, which only arises after switching to use ngrok instead of localhost. This challenge has me puzzled as to why it isn't working as expected.

https://i.sstatic.net/K09ur.png

HttpErrorResponse
error
: 
error
: 
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad...

In conclusion, the backend call defined in NestJS looks like this:

@Controller('drinks')
export class DrinksController {
    constructor(private drinksService: DrinksService, private salesHistoryService: SalesHistoryService) {}
    private readonly logger = new Logger(DrinksController.name);

    @Get()
    async getDrinks(@Res() res: Response) {
        this.logger.log("GET: getDrinks()")
        res.set('Access-Control-Allow-Origin', '*');
        res.send(this.drinksService.getAllDrinks());
    }
...continued code example...
}

Answer №1

The response you receive includes a warning message, identified by code ERR_NGROK_6024. To resolve this issue, simply add the ngrok-skip-browser-warning header to your request.

Source: ngrok has introduced a new interstitial page warning for free account users (ERR_NGROK_6024)

To implement this change, consider creating a method that will be invoked with each request. Here's an example:

// adjust as necessary..
private getHeaders() {
  const headers = new HttpHeaders({
    'ngrok-skip-browser-warning':  '69420'
  });
  return {headers};
}


//...

this.http.get<Drink[]>(this.url, this.getHeaders())

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The TS2339 error has occurred because the "email" property cannot be found on the specified "Object" type

I encountered an issue while using Angular 5, here is the code snippet : signIn(provider) { this._auth.login(provider).subscribe( (data) => { console.log(data); this.hideForm = false; this.emaill = data.email; ...

Executing an Angular 5 function directly from an Android WebView

I am attempting to invoke an Angular 5 function from my Android WebView. Within the Android code: if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT){ this.mWebView.evaluateJavascript("fooBar();", null); } else { this.mWebVi ...

Learn how to resubscribe and reconnect to a WebSocket using TypeScript

In my Ionic3 app, there is a specific view where I connect to a websocket observable/observer service upon entering the view: subscribtion: Subscription; ionViewDidEnter() { this.subscribtion = this.socket.message.subscribe(msg => { let confi ...

Examining React components with Enzyme for event usage in components

Struggling with testing react components that utilize event.target in events has been a challenge for me. Take for example the component code snippet below; import * as React from 'react'; import { generateGuid } from '../../../utilities/Gu ...

Web Worker Integration for Standard Sensor API

Currently, I am developing a Progressive Web App using Ionic 4. While I can utilize the Generic Sensor API in the main thread, my goal is to incorporate it into a Web Worker for reading device motions (such as accelerometer, gyroscope, etc.) with an event ...

Exploring the power of a mapped type within a tuple

Can TypeScript ensure the validity of key-value tuples in this function? function arrayToObject(array, mapper) { const result = {}; for(const item of array) { const [key, value] = mapper(item); result[key] = value; } return ...

Observer function simulated by SinonStub

I am currently testing express middleware using sinon.js My goal is to verify that it sends a specific JSON response and prevents the request from moving on to the next middleware or request handler. const middleware = (req: Request, res: Response, nex ...

Manipulate data in a component with Angular's behavior subject, then reflect these changes in a separate component

In my app, I have two components that are not related to each other and one service available. When a user clicks on comp1, I want to set a Boolean value to true in both comp1 and comp2. However, when I tried using behavior subject to achieve this, the c ...

Using Angular to convert multiple JSON objects into objects on a map

I am facing a challenge with merging multiple JSON objects into one unified object. The issue lies in the fact that these JSON objects have mismatched "keys". Could you provide assistance in finding a solution to this dilemma? Here is an example of JSON ...

Using Angular with Web API to transmit FormFile data from client to API

I am facing a challenge with creating an object (referred to as a "Ticket") along with 0-n children (known as "Attachments") in my Angular application and sending this information to my dotnet core Web API. However, this is more of a logical inquiry that I ...

What is the best way to convert Angular form data into a POST request that the server can process?

In search of a solution to properly send data to the server in a format that it can accept. Currently, the title and descriptions are being successfully transmitted but the ratings are not coming through. It should be noted that there will be more than two ...

Angular 12: How to detect when a browser tab is closing and implement a confirmation dialog with MatDialog

I have a scenario where I am checking if the browser tab is closed using the code below. It currently works with windows dialog, but I would like to incorporate MatDialog for confirmation instead. @HostListener('window:beforeunload', ['$eve ...

Struggling to identify the memory leak in my Express.js Jest tests

Lately, I've been investing a considerable amount of time into identifying memory leaks within my Jest tests. While I have managed to resolve some issues, there is still a noticeable amount of memory leakage occurring from one test suite to the next. ...

Create an object with no specified keys

I am attempting to create an empty object without specifying initial values. Here is my interface: interface MyDate { day: string; month: string; year: string; } This is my class: export class MyClass implements OnInit { date: MyDate = {}; // Err ...

A React component featuring a nested map function should always include a "unique key" prop for each element

I am trying to figure out how to assign a proper Key Value in this component: {var.map((building, index) => { const handles = building.buildingVertices.map((point) => { return ( <DrawingHandle key={`${i ...

Using the hash(#) symbol in Vue 3 for routing

Even though I am using createWebHistory, my URL still contains a hash symbol like localhost/#/projects. Am I overlooking something in my code? How can I get rid of the # symbol? router const routes: Array<RouteRecordRaw> = [ { path: " ...

JavaScript's Array.map function failing to return a value

Here is a snippet of code from an api endpoint in nextJS that retrieves the corresponding authors for a given array of posts. Each post in the array contains an "authorId" key. The initial approach did not yield the expected results: const users = posts.ma ...

When incorporating an array as a type in Typescript, leverage the keyof keyword for improved

I am facing a situation where I have multiple interfaces. These are: interface ColDef<Entity, Field extends keyof Entity> { field: Field; valueGetter(value: Entity[Field], entity: Entity): any } interface Options<Entity> { colDefs ...

What could be causing the parameter "id" to be undefined in Nest JS

Exploring the layout of the project directory, I am currently utilizing yarn berry for the monorepo setup with two distinct packages. The first package houses all the applications, while the second one contains shared libraries and modules. `- apps bff ...

Creating multiple Firestore projects as services in Angular 18 with standalone components: A step-by-step guide

Currently, I am in the process of setting up multiple Angularfire Firestore projects as injectable services for my Angular 18 project. This is the strategy I have come up with: main.ts bootstrapApplication(AppComponent, { providers: [ provideFirebas ...