访问正文

时间:2018-04-09 06:29:11

标签: node.js google-cloud-platform

我想使用谷歌功能来处理一些帖子数据并将其返回。虽然它在本地运行良好,但我无法在谷歌服务器上运行。

这个'功能':

exports.helloWorld = (req, res) => {
  res.set('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS, POST');
  res.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.set('Access-Control-Allow-Origin', '*');
  //res.status(200).send({"req.body.message": req.body.message});
  res.status(200).send({"req.body.message.length": req.body.message.length});
  return;
};

将因此请求失败:

fetch("https://us-central1-{myproject}.cloudfunctions.net/demo",
    {
      body: JSON.stringify({"message":"hello"}),
      method: "POST",
      headers: {
        'Content-Type': 'application/json'
      },
      mode: "cors"
    }
  ).then(response => response.json())
    .then(d => console.log(d))

TypeError: Cannot read property 'length' of undefined
    at exports.helloWorld (/user_code/index.js:17:76)
    at ...

虽然与其他res.status ...行注释相同的方法将起作用并返回{req.body.message:“hello”}

在当地这是有效的..任何想法为什么会破坏?

2 个答案:

答案 0 :(得分:2)

问题是,我没有检查request.method。浏览器发出了预检OPTIONS请求 - 这个失败了,因为那里没有req.body.message。所以真正的POST请求从未发生过。

这解决了它:

  exports.helloWorld = (req, res) => {
      if (req.method === 'POST') {
      res.set('Access-Control-Allow-Origin', '*')
        .set('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS, POST')
        .set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
        .set('Access-Control-Allow-Credentials', false)
        .status(200).send({"req.body.message.length": req.body.message.length });
      }
      else {
        res.set('Access-Control-Allow-Origin', '*')
        .set('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS, POST')
        .set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
        .set('Access-Control-Allow-Credentials', false)
        .status(200).send();
      }
    };

答案 1 :(得分:0)

尝试以下内容:

res.set('Access-Control-Allow-Origin', '*')
    .set('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS, POST')
    .set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
    .set('Access-Control-Allow-Credentials', false)
    .status(200).send({"req.body.message": req.body.message.length });