[英]How do you access the url query params in nodejs?
如何使用typescript訪問nodejs中的url查詢參數? 我嘗試過的在這里?
/**
* 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");
錯誤是'string |類型的參數。 字符串[]'不可分配給'n umber'類型的參數。
在路由處理中間件中,有路由器回調的req, res, next
參數。 您正在尋找req.query。[您的查詢參數]。
對於打字稿,您需要創建一個擴展express.Request的接口,並在其中添加查詢參數。 然后將該類型分配給您的請求參數。
interface myReq extends express.Request {
query: {
[Whatever params you have in your route]: string;
}
}
router.get("/", (req: myReq, res, next) => {
...
})
您還必須在文件中導入快遞
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.