如何将云功能的自定义域用作POST请求

时间:2017-12-26 15:58:06

标签: javascript node.js firebase express google-cloud-functions

我对Node.js的经验不是很熟悉,但学习快速的东西对javaScript来说都很好。我正在使用Cloud Functions为项目创建API,并尝试使用自定义域来访问此API。在我的Firebase托管中,我已连接子域“api.mydomain.com”。

我的函数index.js上有一个名为“api”的函数,使用express:

\begin{tabularx}{24cm}{|X|X|X|X|X|X|X|}

在我的firebase.json中,我有一个重写:

let express = require('express');
let app = express();

app.post('/endpoint/:userId', (req, res) => {

  ... EXECUTE CODE 

  res.json(json);  

});

exports.api = functions.https.onRequest(app);

所以理论上如果我向https://api.mydomain/api/endpoint/userID发出POST请求应该执行该函数但是我得到:

无法POST / api / endpoint / userID /

如果我使用默认的firebase URL来访问像https://us-central1-my-proyect.cloudfunctions.net/api这样的功能,那么它可以正常工作。

您是否有任何想法如何正确配置自定义域以使用我的功能?

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

当您使用Express应用程序作为HTTPS功能的目标时,该功能的名称将被添加到托管URL的路径之前,就像调用功能方向时一样。有两种方法可以弥补这一点:

  1. 将前缀路径放在路径路径中:

    app.post('/api/endpoint/:userId', (req, res) => { ... })
    
  2. 创建第二个Express应用程序,用于路由/ api下的所有内容,并将其发送到Cloud Functions:

    app.post('/endpoint/:userId', (req, res) => { ... })
    const app2 = express()
    app2.use('/api', app)
    exports.api = functions.https.onRequest(app2)
    
  3. 无论哪种方式,当您将路径/api/**重写为函数api时,您的函数将被调用。

答案 1 :(得分:2)

我的首选方法是删除前置项,然后继续进行常规流程。

如果我要致电mysite.com/api/process

const PREFIX = "api"
app.use((req, res, next) => {
  if (req.url.indexOf(`/${PREFIX}/`) === 0) {
    req.url = req.url.substring(PREFIX.length + 1);
  }
  next();
});

app.post("/process", (req, res) => {...}

exports[PREFIX] = functions.https.onRequest(app);

并在firebase.json中

"rewrites": [
      {
        "source": "/api/**",
        "function": "api"
      },
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
相关问题