Is there a way to access URL parameters in the back-end using Node.js?

How can I extract querystring parameters email, job, and source from the following URL?

I want to use these parameters in my service class:

@Injectable()
export class TesteService{

    constructor(){}

    async fetchDataFromUrl(urlSite: URL){
        
        const url = new URLSearchParams(urlSite.search)
        const emailParam = url.get("email");
        console.log(emailParam);

    }

}

And in the controller:

@UseGuards(AuthGuard())
@Controller('Test')
export class test{

    constructor(private readonly testeService: TesteService){}

    @Get('loginTest')
    @UsePipes(ValidationPipe)
    async redirect(){
        return await this.testeService.fetchDataFromUrl(url);
    }
}

I tried manually inputting the URL, but VS Code comments out the code. Once I retrieve the parameters from the URL, I need to redirect to another URL. How can I achieve this?

Any advice on accessing querystring parameter values?

Answer №1

After making some adjustments to enable local execution....

test.service.ts

import { Injectable } from "@nestjs/common";

export interface VerificationInput {
    readonly email: string;
    readonly job: string;
    readonly source: string;
}

@Injectable()
export class TestService {

    constructor() { }

    async verifiedingData(verificationInput: VerificationInput) {

        // const url = new URLSearchParams(urlSite.search)
        // const emailParam = url.get("email");
        return {
            "inputEmail": verificationInput.email,
            "inputJob": verificationInput.job,
            "inputsource": verificationInput.source
        };
    }
}

test.controller.ts

import { Controller, UseGuards, Get, UsePipes, ValidationPipe, Query } from "@nestjs/common";
import { TestService } from "./test.service";

// @UseGuards(AuthGuard())
@Controller('Test')
export class TestController {

    constructor(private readonly testService: TestService) { }

    @Get('loginTest')
    @UsePipes(ValidationPipe)
    async redirect(
        @Query('email') email,  // <---- Inject 'email' query param
        @Query('job') job,      // <---- Inject 'job' query param
        @Query('source') source // <---- Inject 'source' query param
    ) {
        return await this.testService.verifiedingData({ email, job, source });
    }
}

Suppositions

The writer intends to access query parameters from the current request context



WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET

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

This error occurred: "Property 'release' cannot be read because it is undefined."

Hello everyone! I'm in need of some assistance. I am trying to test my service tree with a specific structure. Here is an overview of my test: describe(`Service selector`, () => { describe(`getCurrentServiceTree`, () => { it(`should bui ...

No declaration file was found for the module named 'vue2-timepicker'

Overview I integrated the vue2-timepicker plugin into my Typescript/Nuxt.js application. However, I encountered an issue with importing vue2-timepicker. import timepicker from 'vue2-timepicker' Could not find a declaration file for module &apos ...

What is the best way to retrieve the most recent entry in a Firebase real-time database?

Utilizing Firebase's real-time database, I am updating values in a chart as they change. However, my struggle lies in retrieving only the most recent value added to the database. While browsing through limitToLast and 'child_added' do not w ...

What could be causing ESLint to run on its own configuration file while working with Typescript?

I have files named .eslintignore and eslintrc.js in close proximity. The contents of my ignore file are as follows: .eslintrc.js dist/* node_modules/* out-tsc/* However, when I access the eslintrc.js file, an error is triggered: Parsing error: ESLint was ...

The .ts source file is mysteriously missing from the development tool's view after being deployed

When I work locally, I can see the .ts source files, but once I deploy them, they are not visible in any environment. Despite setting my sourcemap to true and configuring browserTargets for serve, it still doesn't work. Can someone help with this issu ...

What is the best way to monitor updates made to a function that utilizes firestore's onSnapShot method?

I am currently working with the following function: public GetExercisePosts(user: User): ExercisePost[] { const exercisePosts = new Array<ExercisePost>(); firebase.firestore().collection('exercise-posts').where('created-by&apo ...

Learn the technique for dynamically modifying Angular components within the main root component during runtime

I am looking to incorporate a dynamic form where the configuration button triggers the switch from app-login-form to login-config-form. app.component.html <div class="container p-5"> <app-login-header></app-login-header> <div cla ...

The setting of the custom user agent in the Chrome Extension Manifest Version 3 is not functioning correctly

We currently have an extension that consists of only two files: manifest.json and background.js Despite the browser (Chrome version 112) not reporting any errors, we are facing an issue where the user agent is not being set to 'my-custom-user-agent&a ...

Protractor Browser Instance Failure

We have encountered an issue with our UI suite failing in Chrome during the login process. Initially, we thought it might be due to upgrading to Chrome 79, as the problems arose simultaneously. Interestingly, the login functionality still works smoothly in ...

How can I apply unique "compilerOptions" settings to a specific file in tsconfig.json file?

Can I apply specific tsconfig options to just one file? Here is my current tsconfig.json: { ... "compilerOptions": { ... "keyofStringsOnly": false, "resolveJsonModule": true, "esModuleInterop": t ...

NextJS middleware API receives an uploaded image file form, but the request is undefined

Currently, I'm utilizing NextJS to handle form data processing and database uploads, with a pit stop at the NextJS API middleware for image editing. pages/uploadImage.tsx This is the client-side code handler. ... async function handleImageUpload(imag ...

Can an entire object be bound to a model in an Angular controller function?

In TypeScript, I have defined the following Interface: interface Person { Id: number; FirstName: string; LastName: string; Age: number; } Within a .html partial file, there is an Angular directive ng-submit="submit()" on a form element. A ...

What is the reason behind being unable to register two components with the same name using React Hook Form?

I have encountered an issue while using the useForm hook from React Hook Form library. Due to the specific UI library I am using, I had to create custom radio buttons. The problem arises when I try to register two components with the same name in the form ...

Generic type input being accepted

I am trying to work with a basic generic class: export class MyType<T>{} In the directive class, I want to create an @Input field that should be of type MyType: @Input field MyType<>; However, my code editor is showing an error that MyType& ...

Typescript classes implementing data hydration and dehydration techniques

Exploring ways to share TypeScript classes or interfaces between a React + TS frontend and node + TS backend. Converting class instances into JSON poses a challenge as TS types are removed during compile time. Considering options for defining objects in a ...

Is it possible to send requests to multiple APIs using a TypeScript event handler?

I'm facing a challenge in pinging multiple APIs within a single function. It seems like it should be possible, especially since each API shares the same headers and observable. I attempted to write a function for this purpose, but unfortunately, it do ...

Triggering an event within a component to execute a specific function in another component

I am working on a component that includes multiple routes such as home, app, and navbar. My goal is to have the encrementcalc() function execute when the navbar button is pressed. I attempted to use the event emitter but was unsuccessful. Can someone prov ...

Encountering an issue when attempting to establish a connection to Redis using a cache manager within a Nest

Incorporating the NestJS framework into my project and utilizing Cash Manager to connect with Redis cache. Successfully connected with Redis, however encountering an error when attempting to use methods like set/get which shows 'set is not a function& ...

Issue with Typescript not recognizing default properties on components

Can someone help me troubleshoot the issue I'm encountering in this code snippet: export type PackageLanguage = "de" | "en"; export interface ICookieConsentProps { language?: PackageLanguage ; } function CookieConsent({ langua ...

Adding key/value pairs to an array of objects in RxJS Observables can be easily

I currently have an Angular app with state management that retrieves data from a database in observables. Here is an example of the interfaces I am working with: interface Service { id: number, name: string, category_id: number, } interface Category ...