當來自 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: []
}
我不知道為什么。有沒有人遇到過這種情況,如何處理?請告訴我。謝謝你。
uj5u.com熱心網友回復:
您應該將您的設定obj為空物件{}:
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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/396880.html
