Retrieve the original HTTP request in Angular before it is sent out

I am currently attempting to retrieve the HTTP requests before they are actually sent to the server.

Initially, I tried creating a HttpIntercepter like this:

@Injectable()
export class HttpLoggingInterceptorProvider implements HttpInterceptor
{
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
  {
    console.log('Request To Be Logged:');
    console.dir(req);

    if(req.body)
    {
      try
      {
        let formData = <FormData>req.body;

        if(formData.has('id_front'))
          console.log(formData.get('id_front'));

        if(formData.has('id_back'))
          console.log(formData.get('id_back'));
      }
      catch(err)
      {

      }
    }

    return next.handle(req);
  }

While this method works well for now, it is not exactly what I am looking for. My goal is to access the final composed request in raw text form rather than objects.

Currently, the console output appears like this

As you can see, I'm unable to extract any meaningful information from it. It's hard to determine the number or content of values that have been set.

However, by programmatically requesting the body's contents, I am able to retrieve the values as shown below:

let formData = <FormData>req.body;

if(formData.has('id_front'))
  console.log(formData.get('id_front'));

if(formData.has('id_back'))
  console.log(formData.get('id_back'));

At least, I now know something exists within the body other than its FormData type...

My main inquiry:

Is there a way for me to capture the raw composed request that will eventually be dispatched to the server?

Answer №1

The reason for this behavior is that the "try" block runs after all other processes have completed. In Angular, HTTP requests are always executed last, so you must retrieve the data from there or find an alternative solution.

Answer №2

One possible solution might involve

console.log(JSON.stringify(req.body))

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

How to Handle Date Formatting in Angular with Ionic

Utilizing the ionic framework to create a hybrid app with Angular, I have encountered an issue with a form that includes two input boxes: one for date and one for time. The date input's value is being saved in the database in this format: Tue Mar 24 ...

The function is failing to trigger when clicked within an Angular 5 app

Hey everyone, I'm facing a minor issue with my Angular 5 project. I am trying to use a common session check method from a shared TypeScript file. This method is used both when the page loads and when the logout button is clicked to redirect the user t ...

The variable 'x' is being referenced before being initialized

Having trouble understanding the tsserver error in this static method from the Logger class. LogLevel const enum LogLevel { ERROR = 0, WARN = 1 } export default LogLevel; Logger static defaultHandler(level: LogLevel, ...message: readonly ...

Export data from Angular Material data table to Excel format

I'm currently utilizing the angular material data table to showcase data in a tabular layout. I have a requirement to add a feature that enables the export of tabular data to an Excel sheet. Unfortunately, I haven't been able to locate any resour ...

Error: R3InjectorError(Environment Injector) - Unable to inject MsalService into MsalService due to NullInjectorError: MsalService provider not found

Can someone help me understand why I am getting this error when trying to integrate MSAL into my Angular app? ERROR NullInjectorError: R3InjectorError(Environment Injector)[MsalService -> MsalService]: NullInjectorError: No provider for MsalService! ...

Rearrange component positions without triggering a re-render

I am currently developing a React page for a chat application with a UI design similar to the image provided (Please disregard the black box for sensor info). https://i.sstatic.net/ErVN8.png Within this page, I have created two separate components: The ...

Angular 13 implementation of a double-loop structure for fetching data from an API

I'm facing an issue with retrieving specific data fields label and svm from a JSON file. The desired fields are nested inside PORTFOLIO > REGROUPEMENT > ELEMENT. You can access the JSON file here. img(1) I've attempted to display the dat ...

How to access a variable from outside a promise block in Angular

Is there a way to access a variable declared outside of a promise block within an Angular 6 component? Consider the following scenario: items: string[] = []; ngOnInit() { const url='SOME URL'; const promise = this.apiService.post(url ...

What is the best way to create a memoized function in React?

I am currently developing an application using react and typescript, and I am facing a challenge in memoizing a function. const formatData = ( data: number[], gradientFill?: CanvasGradient ): Chart.ChartData => ({ labels: ["a", ...

Ionic3(ios) restricted from loading local resource

I encountered an issue with my code Not allowed to load local resource: file:///var/mobile/Containers/Data/Application/AB6EABD9-CAAF-4AE5-91F9-D8042B34EA87/tmp/cdv_photo_002.jpg This is the code snippet causing the problem let cameraOptions = { ...

Android TV with Ionic

I am working on an APK for Ionic on Android TV and I am facing an issue with the arrow controls. The APK runs on the device but the behavior is not correct. When using arrows to shift the app, the focus does not work as expected. It skips some divs. Here ...

Using WebdriverIO with Angular to create end-to-end tests in TypeScript that involve importing classes leads to an error stating "Cannot use import statement outside a module."

I am facing an issue while trying to set up a suite of end-to-end tests using wdio. Some of the tests utilize utility classes written in TypeScript. During the compilation of the test, I encountered the following error: Spec file(s): D:\TEMP\xx& ...

Show pictures stored in S3

I currently have an Amazon AWS S3 Bucket where I store images. Each object in the bucket has its own link, but when I try to open it in a browser, the image downloads instead of displaying directly on the site. This makes it challenging to view the images ...

React-Admin error: Attempting to invoke a built-in Promise constructor without using the new keyword is not allowed

I'm currently facing an issue where I am trying to retrieve data using a hook. Strangely, there are no TypeScript errors appearing, but when I run the code, a console error pops up stating "Uncaught TypeError: calling a builtin Promise constructor wit ...

Is it possible that overwriting my observable variable will terminate existing subscribers?

I am looking for a way to cache an http call and also trigger the cache refresh. My UserService is structured like this: @Injectable() export class UserService { private currentUser$: Observable<User>; constructor(private http: HttpClient) { } ...

Include a conditional statement in ng keypress

When a user types a specific value into a text input, I want to display a specific div. This is what my template looks like: <input type="text" id="jobTitle" (click)="autoCompleteClick()" (keypress)="autoCompleteKeypress()" name="autocomplete" place ...

Methods for loading a font just once? (TypeScript / Three.JS)

My goal is to generate 20 text blocks, all using the same font. However, I encountered an error with the new TextGeometry if the font isn't loaded yet. Currently, I have been creating each text block like so: new THREE.TextGeometry(this.text, { ...

Ways to expand the width of mat-dialog-actions component in Angular 8

Is there a way to make the cancel and save buttons in the dialog window take up the entire available space? If anyone has any suggestions on how to achieve this, please let me know! https://i.sstatic.net/rfQrN.png ...

Error in executing a function within an asynchronous function sequence

Whenever a user logs in, I want to update their data in Firestore. However, the code I am using does not seem to work as expected. It fails to create a custom User object from the firebase.User. Can anyone help me understand why this is happening and how ...

JavaScript and TypeScript: Best practice for maintaining an Error's origin

Coming from a Java developer background, I am relatively new to JavaScript/TypeScript. Is there a standard approach for handling and preserving the cause of an Error in JavaScript/TypeScript? I aim to obtain a comprehensive stack trace when wrapping an E ...