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

Connecting two divs with lines in Angular can be achieved by using SVG elements such as

* Tournament Brackets Tree Web Page In the process of developing a responsive tournament brackets tree web page. * Connection Challenge I am facing an issue where I need to connect each bracket, represented by individual divs, with decorative lines linki ...

Type of object is unidentified in Vuejs with Typescript error code ts(2571)

Currently, I am facing a challenge with storing JSON data in a variable within my Vue project. Below is the code snippet used to upload and store the file: <input type="file" id="file" ref="fileSelect" class="custom- ...

The disappearance of the "Event" Twitter Widget in the HTML inspector occurs when customized styles are applied

Currently, I am customizing the default Twitter widget that can be embedded on a website. While successfully injecting styles and making it work perfectly, I recently discovered that after injecting my styles, clicking on a Tweet no longer opens it in a ne ...

Angular Error: Unable to access property 'users' on a null value

I am working on a component that takes in data through the @Input() decorator regarding a group. My objective is to generate a new array of objects during the initialization of the component based on the data from the group array. Below is the TypeScript c ...

Navigating through Dynamic URL Parameters with RouterLink in an Angular Application

Within my Angular 2 application, there exists a tab section where users can choose from a collection of separate yet contextually connected components. By clicking on one of these links, the corresponding component is loaded based on the routerLink definit ...

Using Angular2 to perform search functions within the Loopback framework

Can anyone assist me with implementing a "wildcard" query using loopback to search data from the database in my angular2 project? Thank you in advance for your help. This is the query I am trying to use: this.model.find({ "where": { "wildcard ...

What is the best method for excluding attributes from a nested model in sequelize?

In my project, there are 2 models called User and Role, and they have a many-to-many relationship. To manage this connection, I introduced a third model named UserRole. The issue arises when the UserRole is also retrieved in the query below: async getUser ...

Is it possible to obtain the URL (including parameters) of the first navigation before proceeding with the navigation process?

My goal is to automatically navigate to a specific website when a certain condition for the URL is met. Consider the following scenario in the ngOnInit() method of app.component.ts: if (urlMatchesCondition()) { await this.router.navigateByUrl('sp ...

Tips on refreshing a view in react as data updates

Currently, I am delving into learning a variety of subjects such as Typescript, Express, and my newfound interests in REACT and RXJS. To aid in my studies, I created a Quick-List on Github, but encountered a question... "How can the view in React be upda ...

Navigating to the main directory in Angular 2

I am currently diving into the world of Angular 2 and attempting to create my very first application. I am following a tutorial from Barbarian Meets Coding to guide me through the process. Following the steps outlined in the tutorial, I have set up my appl ...

Resolve an "Uncaught ReferenceError" by importing an unused component to fix the error of not being able to access a variable before initialization

In my service file, where I store all other services used in the frontend, there is an import section that includes one component even though it is not being used. import { VacationComponent } from 'app/view/vacation/vacation.component'; When I ...

Utilizing Angular 2 for transforming JSON data into Angular classes

I have been working through the Angular2 getting started guide to kickstart my own application development. So far, I have managed to retrieve JSON objects from a local file and display them in angular2 templates. However, the challenge arises when the str ...

Tips for passing TouchableOpacity props to parent component in React Native

I created a child component with a TouchableOpacity element, and I am trying to pass props like disabled to the parent component. Child component code: import React from 'react'; import {TouchableOpacity, TouchableOpacityProps} from 'react- ...

Tips for splitting JSON objects into individual arrays in React

I'm currently tackling a project that requires me to extract 2 JSON objects into separate arrays for use within the application. I want this process to be dynamic, as there may be varying numbers of objects inside the JSON array in the future - potent ...

Issue encountered in ../../../../ Unable to locate namespace 'Sizzle'

Following the execution of npm install @types/jquery, I encountered a compilation issue while running my Angular project with ng serve ERROR in ../../../../../../AppData/Roaming/JetBrains/WebStorm2020.1/javascript/extLibs/global-types/node_modules/@types/j ...

Why should one bother with specifying types when defining a variable in Typescript?

As someone new to Typescript, I've come to appreciate its many advantages when working on larger applications and with multiple team members :) Imagine you have the following TypeScript code: declare const num = 5: number; Why is this better than: ...

Tips for testing FormGroupDirective within a component

I am facing difficulties in testing a component with FormGroupDirective in the viewProviders section. I am unable to create a mock of the parent and set an empty formGroup. The component code is as follows: @Component({ (...) viewProviders: [ ...

Compilation in TypeScript taking longer than 12 seconds

Is anyone else experiencing slow TypeScript compilation times when building an Angular 2 app with webpack and TypeScript? My build process takes around 12 seconds, which seems excessively slow due to the TypeScript compilation. I've tried using both ...

Mocking a third-party callback function in Jest for method implementation

Utilizing Nest + Cognito for user authentication in an application, I have a method within my Authentication service that requires testing/mocking: async cognitoRegister(userPool: CognitoUserPool, { name, password, email }: AuthRegisterInput): ...

What is the process for recording information using a static method in TypeScript within a class?

For my school project, I'm struggling to retrieve the names from a class using a method. One class creates monsters and another extends it. abstract class genMonster { constructor( public id: string, public name: string, public weaknesse ...