dim_dev
dim_dev

Reputation: 359

Axios post with firebase cloud functions

I have a basic firebase cloud function. I want to post a request with Axios (send Slack message). But the server returns "Error: could not handle the request (500)". Where is the problem? I use 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',
            },
          },
        ],
      }
    )
  })
})


Upvotes: 0

Views: 4767

Answers (2)

Curt Bryan III
Curt Bryan III

Reputation: 46

The way to accomplish this is to add the header "Content-Type": "application/x-www-form-urlencoded" to the post. You would do it like this with the code you provided:

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 doesn't seem to play nice with regular JSON, which is the default of Axios, so that is why it needs to be changed.

Hope this fixes it for you!

Upvotes: 1

michael
michael

Reputation: 4173

It seems like you're using cors incorrectly. Also you should return any value using provided response. Check below for detail.

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);
    }
  });
});

Upvotes: 1

Related Questions