【问题标题】:Send JSON Data to Google Cloud Functions using Express.js Routing使用 Express.js 路由将 JSON 数据发送到 Google Cloud Functions
【发布时间】:2020-12-09 11:28:25
【问题描述】:

谁能帮我理解一下,为什么我在调用谷歌云函数时会出错,而如果我在本地调用相同的函数却没有出错。

PFB 函数的代码,我从中调用

const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded());
var n1 = null;
var n2 = null;
app.get('/sum', (req, res) => {
    n1 = Number(req.query.n1 || req.body.n1);
    n2 = Number(req.query.n2 || req.body.n2);
    res.json({
        "n1": n1,
        "n2": n2,
        "result": n1 + n2
    })
});
app.listen(3000);
exports.calculator = app;

调用谷歌云函数的Javascript代码:

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({"n1":1,"n2":2});
var requestOptions = {
  method: 'GET',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};
fetch("https://us-central1-testing-297304.cloudfunctions.net/calculator/sum", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

所有本地或云功能的请求都是通过 Postman 发出的

gcp 给出的错误:

【问题讨论】:

  • 我没有关注这个故事。使用 Cloud Functions,我通常希望看到一个使用 req/res 参数调用的函数。在您的代码示例中,我看到了一个完整的 express.js 应用程序。您能否准确说明部署到 Cloud Function 的内容?您能否描述向调用者报告的错误的确切性质以及写入 Cloud Logging 的任何可能包含其他详细信息的日志?
  • 您好 Kolban,感谢您的快速回复。通过代码,我想检查用户是否获得输出,如果&仅当请求是特定方法(此处为 GET)且具有正确的路由(此处为 /sum)。另外,如果上述函数执行成功,我想添加一个中间件来检查请求的授权令牌。如果不满足上述条件,则该函数应报错。错误:您的客户发出了格式错误或非法的请求。日志:调用函数时没有生成日志

标签: google-cloud-functions express-router


【解决方案1】:

调用您的函数会返回“Cannot GET /sum”错误,因为使用 GET/HEAD 方法的请求不能有 body。您应该将您的请求更改为 POST(在您的代码和 Postman 请求上)。

app.post('/sum', (req, res)

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

我在我的测试功能上这样做了,我能够使用 Postman 获得 200 OK 的输出。

【讨论】:

    猜你喜欢
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多