【问题标题】:req object with express causes UnhandledPromiseRejectionWarning带有 express 的 req 对象导致 UnhandledPromiseRejectionWarning
【发布时间】: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


【解决方案1】:

根据@hoangdv,在某处添加app.use(express.urlencoded())。如果你问我,而不是 node-ish 没有它作为默认值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-11
    • 2021-10-22
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多