类型'string"/>
“类型'string
我正在使用节点+打字稿和集成的招摇工具进行API调用。我有以下要求:
http://localhost:3033/employees/search/?username=test
[我想在这里找到用户名=测试的记录。
因此,我使用URL模块解析查询字符串,如下所示,并在控制台中获取用户名。
var params = URL.parse(req.url, true).query;
console.log(params); //gives me [Object: null prototype] { username: 'test' } in my console
但是每当我尝试将params.username分配给如下所示的常量时
const username:string =params.username;
它给我以下错误
类型'字符串| string []'不可分配给'string'类型。类型'string []'不能分配给类型'string'。
我的完整代码如下
import * as URL from 'url';
public getUserByAge = 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()函数将已解析的查询字符串转换为字符串。
public getUserByAge = 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.findUserByAge(username);
res.status(200).json({ data: findOneUserData, message: 'findOne' });
} catch (error) {
next(error);
}
}
更多推荐
“类型'string
发布评论