【问题标题】:Axios post with firebase cloud functions带有firebase云功能的axios帖子
【发布时间】:2020-11-17 19:44:05
【问题描述】:

我有一个基本的 Firebase 云功能。我想通过 Axios 发布请求(发送 Slack 消息)。但是服务器返回“错误:无法处理请求(500)”。哪里有问题?我用的是cors。

const cors = require('cors') 
const functions = require('firebase-functions')
const Axios = require('axios')

exports.sendMessage = functions.https.onRequest((request, response) => {
  return cors()(request, response, () => {
    return Axios.post(
      `https://hooks.slack.com/services/*XXXXXXXXXXXXX*`,
      {
        blocks: [
          {
            type: 'section',
            text: {
              type: 'mrkdwn',
              text: 'hello',
            },
          },
        ],
      }
    )
  })
})


【问题讨论】:

  • 我使用 Firebase 免费计划,但我使用 Node 8 作为依赖项,它应该可以在明年之前使用这个免费计划。
  • 请编辑问题以显示您在函数控制台中看到的任何错误。没有它,我们必须猜测这里发生了什么。

标签: javascript node.js axios google-cloud-functions


【解决方案1】:

您似乎错误地使用了cors。此外,您应该使用提供的response 返回任何值。详情请查看下方。

const cors = require('cors')({origin: true});

exports.sendMessage = functions.https.onRequest((request, response) => {
  return cors(request, response, async () => {
    try {
      const res = await Axios.post(
        `https://hooks.slack.com/services/*XXXXXXXXXXXXX*`,
        {
          blocks: [
            {
              type: 'section',
              text: {
                type: 'mrkdwn',
                text: 'hello',
              },
            },
          ],
        },
      );
      response.status(res.status).json(res.data);
    } catch (error) {
      response.status(400).json(error);
    }
  });
});

【讨论】:

  • 通常它会工作,但现在我收到错误 getaddrinfo EAI_AGAIN hooks.slack.com:443,可能是因为当您使用 Google 时,Google 不允许您进行出站网络(Google 服务除外)火花计划。
【解决方案2】:

实现这一点的方法是在帖子中添加标题 "Content-Type": "application/x-www-form-urlencoded"。您可以使用您提供的代码来执行此操作:

const cors = require('cors') 
const functions = require('firebase-functions')
const Axios = require('axios')

exports.sendMessage = functions.https.onRequest((request, response) => {
  return cors()(request, response, () => {
    return Axios.post(
      `https://hooks.slack.com/services/*XXXXXXXXXXXXX*`,
      {
        blocks: [
          {
            type: 'section',
            text: {
              type: 'mrkdwn',
              text: 'hello',
            },
          },
        ],
      },
      {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      }
    )
  })
})

Slack API 似乎不适用于常规 JSON,这是 Axios 的默认设置,因此需要对其进行更改。

希望这可以为您解决问题!

【讨论】:

    猜你喜欢
    • 2020-10-30
    • 2017-10-28
    • 2018-04-11
    • 1970-01-01
    • 2021-01-12
    • 2020-06-09
    • 2018-08-12
    • 2018-11-29
    • 2018-05-09
    相关资源
    最近更新 更多