我正在使用 node + typescript 和集成的 swagger 进行 API 调用.我大摇大摆地提出以下要求
I am using node + typescript and integrated swagger for API Calls. I have a following request in swagger
localhost:3033/employees/search/?username=test
这里我要查找 username = test 的记录.
所以我使用 URL 模块解析查询字符串,如下所示,我在控制台中获取用户名.
So I parse the query string using URL module, like below and I am getting the username in my console.
var params = URL.parse(req.url, true).query; console.log(params); //gives me [Object: null prototype] { username: 'test' } in my console但每当我尝试将 params.username 分配给如下常量时
But whenever I try to assign params.username to a constant like below
const username:string =params.username;它给了我以下错误
键入'字符串 |string[]' 不可分配给类型 'string'.类型 'string[]' 不能分配给类型 'string'.
Type 'string | string[]' is not assignable to type 'string'. Type 'string[]' is not assignable to type 'string'.
我的完整代码如下
import * as URL from 'url'; public getUserByName = async (req: Request, res: Response, next: NextFunction) => { var params = URL.parse(req.url, true).query; const username:string =params.username; try { const findOneUserData: Employee = await this.userService.findUserByName(username); res.status(200).json({ data: findOneUserData, message: 'findOne' }); } catch (error) { next(error); }}
推荐答案好的,所以我得到了我犯的错误.第一个是@ford04 在评论中提到的.我直接将 Object 分配给字符串.我在我的问题中改变了它.第二个是通过 toString() 函数将解析的查询字符串转换为字符串.
Okay ,so I got the mistake that I made. The first one was what @ford04 has mentioned in the comment. I was directly assigning Object to the string. I changed it in my question. The second was converted the parsed query-string to string by toString() function.
public getUserByName = async(req: Request, res: Response, next: NextFunction) => { var params = URL.parse(req.url, true).query; console.log(params.username); const username: string = params.username.toString(); //this is the key try { const findOneUserData: Employee = await this.userService.findUserByName(username); res.status(200).json({ data: findOneUserData, message: 'findOne' }); } catch (error) { next(error); } }更多推荐
"键入'字符串
发布评论