【发布时间】:2021-04-17 06:22:44
【问题描述】:
我已从 Google 的数据存储教程中改编了以下代码。我隐约知道 Promises,并且我正在使用 await 我可以弄清楚的地方。我已经使用了req 对象,如下所示,没有发生任何事件,但这里似乎是空的。
它会导致这个错误:
2021-04-16 04:55:03 default[20210415t215354] (node:10) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'name' of undefined
[剪辑]
name 是对我指定的参数的引用:
curl -X POST https://MYURL/gizmos --data 'name=foo&type=bar&len=29'
我做错了什么?我该如何避免这种情况?
/**
* @param {object} gizmo The gizmo record to insert.
*/
const insertGizmo = gizmo => {
return datastore.save({
key: datastore.key('gizmo'),
data: gizmo,
});
};
/**
* Retrieve the latest gizmo
*/
const getLastGizmo = () => {
const query = datastore
.createQuery('gizmo')
.order('createTime', {descending: true})
.limit(1);
return datastore.runQuery(query).then( (entities) => {
return entities[0].map(fromDatastore);
});
};
//Create a Gizmo
app.post('/gizmos', async (req, res, next) => {
const createTime = new Date();
const gizmo = {
name: req.body.name,
type: req.body.type,
length: req.body.len,
createTime: createTime,
};
try {
await insertGizmo(gizmo);
const newGizmo = await getLastGizmo();
//const [newGizmos] = await getLastGizmo();
await insertGizmo(gizmo);
const newGizmo = await getLastGizmo();
//const [newGizmos] = await getLastGizmo();
const gizmoUrl = "https://MYURL/gizmos/"+newGizmo.id;
const resText = {
"id" : newGizmo.id,
"name" : newGizmo.name,
"type" : newGizmo.type,
"length" : newGizmo.length,
"self" : gizmoUrl,
};
res.status(201).set('Content-Type', 'text/plain').send(resText).end();
} catch (error) {
next(error);
}
});
【问题讨论】:
-
注册
express.urlencoded()为您的快递应用程序。 -
那是票!
标签: node.js express promise datastore