Friday 1 May 2020

Debugging Angular using proxies to the real Backend API in Visual Studio Code

One of the problems of having separate Frontend and Backend is not being able to test against actual, real API on your Backend.

Sure you can fire up your Angular project using 'ng serve' and run against a bunch of mock data, but that is not testing your software.

What you actually want is to be able to debug the Frontend against your real Backend API as the Angular project would when its compiled into your Backend.


To be able to do this, you must write a proxy into your Angular project, to re-write HTTP requests using Angular HTTPInterceptor.

import { HttpInterceptor, HttpRequest } from '@angular/common/http/';
import { HttpHandler } from '@angular/common/http';

export class MyApiHttpInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler) {
        // Rewrite api calls to proxied Backend.
        req = req.clone({ url: `http://backendService.com:9000/${req.url}` });
        return next.handle(req)
    }
}


In your Angular app.module.ts, wire up the proxy through the providers.
providers: [
  { provide: HTTP_INTERCEPTORS, useClass: MyApiHttpInterceptor, multi: true },
]


Then to debug your project, you install VS Code extension Debugger for Chrome.
Configure your VS Code Debug Launcher settings (.vscode\launch.json) with the following options from default, but adjust the ports as you need.
Also take note that your workspace has to be correct to your Angular project root.
Also notice that we to disabled CORS and enabled Chrome Incognito Mode so that we are able to call to proxied Backend API.

{
 // Use IntelliSense to learn about possible attributes.
 // Hover to view descriptions of existing attributes.
 // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
 "version": "0.2.0",
 "configurations": [
  {
   "type": "chrome",
   "runtimeArgs": ["--disable-web-security", "--incognito"],
   "request": "launch",
   "name": "Launch Chrome against localhost",
   // "url": "http://localhost:8080/",
   "url": "http://localhost:4200/",
   // "webRoot": "${workspaceFolder}",
   "webRoot": "${workspaceFolder}/AngularFolder"
  }
 ]
}

No comments:

Post a Comment