How to send parameters with the fetch API

After completing a task that involved converting code from Angular HttpClient to using fetch API, I encountered an issue with passing parameters. Below is the original code snippet before my modifications:

let activeUrl = new URL(this.serverAddress);
        let targetUrl = activeUrl.origin + environment.apiBasePath + '/named_selection/' + componentId;
        let params = new HttpParams().set('name', name);

        if (this.customLookupAddress != "") {
            params.set('lookup', this.customLookupAddress);
        }

        if (this.customGatewayAddress != "") {
            params.set('gateway', this.customGatewayAddress);
        }

        return this.httpClient.get(targetUrl, { headers: { 'responseType': 'json' }, params: params }).pipe(
            map((namedSelection) => {
                this.namedSelections.set(componentId.toString() + '.' + name, namedSelection);

Below is the revised code where I converted the entire logic to use the fetch API:

let activeUrl = new URL(this.serverAddress);
        let targetUrl = activeUrl.origin + environment.apiBasePath + '/named_selection/' + componentId;
        let params = new HttpParams().set('name', name);

        if (this.customLookupAddress != "") {
            params.set('lookup', this.customLookupAddress);
        }

        if (this.customGatewayAddress != "") {
            params.set('gateway', this.customGatewayAddress);
        }
        const data$ = new Observable(observer => {
            fetch(targetUrl, { headers: { 'responseType': 'json'}, method: 'GET'})
              .then(response => response.json()) 
              .then(namedSelection => {
                observer.next(namedSelection);
                observer.complete();
              })
              .catch(err => observer.error(err));
          });
               
        return data$.pipe(
             tap((namedSelection) => {
                this.namedSelections.set(componentId.toString() + '.' + name, namedSelection);
             })
        );
    }

I am currently facing a challenge in passing the 'params' in the fetch request. Can you provide guidance on how to address this and suggest any necessary changes to the structure of the code within the fetch function?

Answer №1

If you want to include URL parameters in a fetch request, you can do so by adding them to the fetch URL and ensuring that the correct header names are set:

const params = new URLSearchParams({ type });

if (this.customQueryAddress) {
  params.set('query', this.customQueryAddress);
}
if (this.customEndpointAddress) {
  params.set('endpoint', this.customEndpointAddress);
}
fetch(`${requestUrl}?${params}`, { headers: { 'Accept': 'application/json' } })
  .then(res => res.json())
  // ...

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 resolve TypeScript error TS2322 when a function returns an interface

export interface AWSTags { CreatedBy: string; Environment: EnvironmentMap; Name: string; OwnedBy: string; Platform: string; Product: string; Runbook: string; Service: string; } Another script contains the following function to generate an ...

Property does not exist on object error is thrown by Angular httpClient.getResult

constructor(private http: HttpClient) { } ngOnInit() { this.http.get('url').subscribe(data => { console.log(data); console.log(data.login); }); } } When looking at the data in the console, I noticed that the property &ap ...

Incorporate a JavaScript array into a TypeScript document

Having a file named array.js with a large collection of strings, structured like this: module.exports = ["word1","word2",...] I attempted to utilize this array in my validation.ts file by adding the following line: let wiki = require('./array.js&a ...

Setting a background image in vanilla-extract/css is a straightforward process that can instantly enhance

I am brand new to using vanilla-extract/CSS and I have a rather straightforward question. I am attempting to apply a background image to the body of my HTML using vanilla-extract, but I am encountering issues as I keep getting a "failed to compile" error. ...

Issue with the functionality of the material tree's parent node may not be operating

I created a material tree with the ability to select up to 42 elements. Once the limit is reached, the nodes become disabled. However, I encountered an issue where if some child nodes are selected while others are disabled due to reaching the limit, the pa ...

I'm having trouble retrieving the information as it is showing as undefined. Can anyone offer any advice?

Attempting to extract specific information from an API response has proven challenging. Despite my efforts to isolate the desired data, all listed details appear as undefined. import { HttpClient } from '@angular/common/http'; import { Injectable ...

Ways to resolve the Ionic v1 deprecation error problem

I am facing a problem with an Ionic v1 deprecation error, causing it to not work properly. ionic build ios ionic emulate android The basic commands are failing to produce the desired outcome. Is there a way to resolve this issue? Note: My application is ...

Having trouble installing Angular Material due to a getaddrinfo ENOTFOUND error?

When attempting to execute ng add @angular/material in my Angular project, I encountered the following error: Unable to fetch package metadata: request to http://registry.npmjs.org/@angular%2fmaterial failed, reason: getaddrinfo ENOTFOUND proxy.{companyna ...

Encountering a Windows 11 issue: npm ERR! errno -4058 with ENOENT bash code

Encountered a troublesome NPM issue suddenly, after taking a brief break from working on my project. Facing the following error with core-js. npm ERR! code ENOENT npm ERR! syscall spawn bash npm ERR! path C:\Users\User1\Documents\projec ...

The Angular router is throwing a "TS2339: Property 'navigate' does not exist on type 'Route'." error message

I'm really struggling with this issue. Why is the 'navigate' property not available to use? When attempting to use it, I receive the error message "TS2339: Property 'navigate' does not exist on type 'Route'." For more in ...

Utilizing Typescript for parsing large JSON files

I have encountered an issue while trying to parse/process a large 25 MB JSON file using Typescript. It seems that the code I have written is taking too long (and sometimes even timing out). I am not sure why this is happening or if there is a more efficien ...

Inability to assign a value to an @input within an Angular project

I recently started using Angular and I'm currently trying to declare an input. Specifically, I need the input to be a number rather than a string in an object within an array. However, I'm encountering difficulties and I can't figure out wha ...

React Query successfully retrieves the path, but unfortunately fails to render the image in the display

Currently facing an issue where I am trying to retrieve images from the backend using ReactQuery. Here is the ReactQuery code snippet: export const useGetProductImagesByProductId = (productId: string) => useQuery({ queryKey: ['productIm ...

Scrolling to the bottom of an ion-content in Ionic 4

I am currently developing a chat page with Ionic 4 and I'm attempting to implement an automatic scroll feature to the bottom of the page. However, the method I tried using doesn't seem to be working as expected: import { IonContent } from "@ioni ...

Update current properties of objects

I'm feeling like I'm going crazy and could really use some assistance. My predicament involves a function that looks like this: private generateTimeObject(firstObject: someInterface, secondObject?: someInterface) { let firstTime; let secondTi ...

Having trouble retrieving information from hash fetch fragment following authentication redirection in Angular 4

Once the authorization process is complete, the browser will be redirected to the following URL: &token_type=bearer&state=XYZ&expires_in=3599 However, just before I can retrieve the details, everything seems to disappear and the browser' ...

Incorporating traditional Javascript classes for modeling in React development

Can traditional JavaScript classes be utilized in models within the MVC framework while using React, as opposed to relying on Redux or contexts & reducers which may impact reusability? If this approach is feasible, how can we efficiently 'subscribe&ap ...

Error: Unable to locate module with associated type definitions when utilizing Typescript in Next.js

Currently, I am working on a next.js project that I'm attempting to integrate typescript into. The structure of my folders is organized as follows: api aggregation.ts interfaces index.ts components Component1 index.js index.module.css ...

What is the best way to transmit a JSON object to a .NET server utilizing SignalR?

I am currently in the process of developing an Angular application that requires sending data from Angular forms to an external server using a .NET Core server and SignalR. While I have successfully established a connection between the Angular client and c ...

Bringing a JavaScript function into a TypeScript file results in it being treated as a namespace

Trying to bring a vanilla JavaScript function into a TypeScript file within a React Native app has presented some challenges. The import process goes smoothly when working with JS, but switching to TS triggers the error message: Cannot use namespace &apos ...