繁体   English   中英

TypeScript: API 总是返回空的 object { [key: string]: any }

[英]TypeScript: API alway return empty with object { [key: string]: any }

当来自 API 的响应数据始终为空时,我遇到了问题。 下面的示例代码:

interface DataStore {
    [key: string]: any,
}

static GetData = async (req: Request, res: Response): Promise<Response> => {
    let obj: DataStore = [];
    obj['id'] = 'account';
    obj['pwd'] = 'password';
    console.log(obj); // can see data: [ id: 'account', pwd: 'password' ]
    res.status(200).send(obj); // it return empty: []
}

我不知道为什么。 有没有人遇到过这种情况,如何处理? 请告诉我。 谢谢你。

您应该将obj设置为空的 object {}

 const t1 = [] t1['foo'] = 'foo' t1['bar'] = 'bar' console.log(JSON.stringify(t1)) // [] const t2 = {} t2['foo'] = 'foo' t2['bar'] = 'bar' console.log(JSON.stringify(t2)) // {foo: 'foo', bar: 'bar'}

因此,在您的代码中,请执行以下操作:

interface DataStore {
  id?: string,
  pwd?: string,
}

// No need for `async` here since there is no `async` code here
static GetData = (req: Request, res: Response): void => {
  const obj: DataStore = {};
  obj['id'] = 'account';
  obj['pwd'] = 'password';
  
  res.status(200).json(obj);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM