“类型'string

编程入门 行业动态 更新时间:2024-10-10 13:13:08

“<a href=https://www.elefans.com/category/jswz/34/1771355.html style=类型'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

本文发布于:2024-05-07 01:16:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1754050.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!