如何使用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的参数 琥珀色”。
答案 0 :(得分:1)
在路由处理中间件内部,有路由器回调的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) => {
...
})
如果还没有,您还必须在文件中导入快递