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'.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.