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...
}