首页 > 解决方案 > 带有firebase云功能的axios帖子

问题描述

我有一个基本的 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',
            },
          },
        ],
      }
    )
  })
})


标签: javascriptnode.jsaxiosgoogle-cloud-functions

解决方案


看来您使用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);
    }
  });
});

推荐阅读