http post请求firebase云功能

时间:2018-04-15 19:14:05

标签: http firebase post google-cloud-functions

我想在firebase云功能中发布请求并将数据发送到body。 默认情况下,是获取请求还是发布请求?

 var functions = require('firebase-functions');

exports.tryfunction= functions.https.onRequest((req, res) => {
    console.log(req.body) // or it should be req.query 
});

我如何知道并决定它的方法是什么?

3 个答案:

答案 0 :(得分:2)

我只是分享简单的代码部分。我是这样使用的。

const functions = require('firebase-functions');


 exports.postmethod = functions.https.onRequest((request, response) => {
  if(request.method !== "POST"){
    response.send(405, 'HTTP Method ' +request.method+' not allowed');
    }

  response.send(request.body);
 });

我希望它会有所帮助。

答案 1 :(得分:1)

没有默认值。请求方法是客户选择发送的任何内容。

回调中的query = (Movie .select(Movie, PlaylistMovie.position) .join(PlaylistMovie) .where(PlaylistMovie.playlist == playlist) .order_by(PlaylistMovie.position)) for movie in query: print(movie.name, movie.playlistmovie.position) 对象是express.js Request对象。使用链接文档,您可以看到使用req.method可以找到请求方法。

答案 2 :(得分:0)

要指定Firebase Function接受的HTTP方法,您需要像通常在标准Express应用程序中一样使用Express API。

您可以将完整的Express应用程序作为onRequest()的参数传递给HTTP函数。这样,您可以使用Express自己的API将Firebase函数限制为特定方法。这是一个示例:

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

// Add middleware to authenticate requests or whatever you want here
app.use(myMiddleware);

// build multiple CRUD interfaces:
app.get('/:id', (req, res) => res.send(Widgets.getById(req.params.id)));
app.post('/', (req, res) => res.send(Widgets.create()));
app.put('/:id', (req, res) => res.send(Widgets.update(req.params.id, req.body)));
app.delete('/:id', (req, res) => res.send(Widgets.delete(req.params.id)));
app.get('/', (req, res) => res.send(Widgets.list()));

// Expose Express API as a single Cloud Function:
exports.widgets = functions.https.onRequest(app);

上面的代码说明: 我们使用Express自己的API公开了带有端点/widgets的Firebase函数,该端点具有用于不同HTTP方法的不同处理程序,例如app.post(..)app.get(..)等。然后,我们将app作为参数传递给functions.https.onRequest(app);。就是这样,您就完成了!

您甚至可以根据需要添加更多路径,例如如果我们想要一个接受GET请求的端点到看起来像/widgets/foo/bar的端点,我们只需添加app.get('/foo/bar', (req, res => { ... });

所有内容都直接来自official Firebase docs。 我很惊讶@Doug Stevenson在他的回答中没有提到这一点。

相关问题