1

I am using Vercel serverless function to run a post request to webhook. This works correctly on localhost but not working after deploying to Vercel serverless function.

async function formSubmission(req, res) {
  res.statusCode = 200;
  console.log('form-submission-init');
  axios({
    method: 'POST',
    url: 'https://flow.zoho.in/*',
    data: req.body,
  })
    .then((response) => {
      console.log('success');
    })
    .catch((error) => {
      console.log('fail', error);
    });
  res.json({ data: 'done' });
}

Vercel logs form-submission-init Vercel logs do not print either fail or success

I have gone through Vercel's documentation on why it may not work link but unsure. Any help appreciated.

2 Answers 2

4

You have async flow problem, you are sending response res.json before axios promise is actually resolved.

You either need to await axios request, or put res.json inside promise chain.

Sign up to request clarification or add additional context in comments.

Comments

0

I have encountered this problem recently, but I finally solved it. This is my code, and I hope it can help you.

const axios = require('axios')

module.exports = async (req, res) => {
    const json = req.body;

    let output = parseData(json);

    let data = {
        msg: output
    };

    // webhook
    if (output.startsWith("The price is")) {
        let price = output.match(/\d+\.\d+/)[0];
        // Use await to wait for the webhook request to finish
        try {
            await sendWebhook(price);
            console.log("Webhook request sent successfully!");
        } catch (error) {
            console.log("Error sending webhook request:", error);
        }
    }

    // Send the response after the webhook request is resolved
    res.status(200).json(data);
};

function sendWebhook(price) {
    let msg_url = `http://api.xxxxx.app/Va5GhE/${price}`;
    let config = {
        method: 'post',
        maxBodyLength: Infinity,
        url: msg_url,
        headers: {}
    };

    // Return the axios promise so that it can be awaited in the calling function
    return axios.request(config);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.