简体   繁体   中英

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

I have issue when response data from API alway empty. Sample code below:

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: []
}

I don't know why. Has anyone encountered this, and how to handle it? Please let me know. Thank you.

You should set your obj to an empty 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'}

So, in your code, do the following:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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