0

How do you access the url query params in nodejs with typescript? What I tried is here?

    /**
 * My Server app
 */
import * as Http from "http";
import * as url from "url";
import { HttpServer } from "./HttpServer";
import { TaxCalculator } from "./TaxCalculator";
export interface myReq extends Http.IncomingMessage {
  amount: string;
  rate: string;
}
/**
 * MyServer class
 * Create MyServer from HttpServer
 */
class MyServer extends HttpServer {
  /**
   * Create a new NodeServer object
   * @param port Port number of the server
   * @param name Name of the server
   */
  constructor(port: number, name: string) {
    super(port, name);
  }
  /**
   * Handle the Request in request nad populate the response to response
   * @param request Incoming Request
   * @param response Outgoing Response
   */
  onRequest(request: myReq, response: Http.ServerResponse): void {
    response.writeHead(200, {"Content-Type": "text/plain"});
// const { amount, rate } = url.parse(request.url, true).query;
    const query = url.parse(request.url, true).query;
    const tc = new TaxCalculator();
    const tax = tc.calculate(query.amount, query.rate);
    response.end(JSON.stringify(tax));
  }
}

// Create a server instance
const port = 8080;
new MyServer(port, "Test server");

The error is Argument of type 'string | string[]' is not assignable to parameter of type 'n umber'.

1 Answer 1

2

Inside your route handling middleware there are the req, res, next parameters of the router callback. You are looking for req.query.[your query param].

For typescript, you'll want to create an interface that extends express.Request and add your query param there. Then assign that type to your request param.

interface myReq extends express.Request {
    query: {
        [Whatever params you have in your route]: string;
    }
}

router.get("/", (req: myReq, res, next) => {
  ...
})

Youll also have to import express in the file if you havent already

Sign up to request clarification or add additional context in comments.

4 Comments

Show me how to do that
Oh youre not using express are you? That would exppain that. I highly recommend looking into express (unless you are trying to master plain node for practice purposes). Look up express and express generator on the express website. Express is a node framework that makes handling the server stuff easier. Express generator is a starter server itll setup for you to extend. If you are new to node servers looking at the example server can be edifying.
I only want to do it with nodejs
there are situations where you cannot use express. I am also looking for this solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.