Using Netlify functions, fetch POST request won't send from within an Express callback

For context, I have a Serverless function that uses Express to receive data from a Webhook Event.
The first callback receives that data, the second callback should obtain an access token and post our data to an external server using fetch Post requests.

The code works well locally testing with Postman, but when I deploy to Netlify, run a Postman test and check the Netlify logs, the logs show the data is received, but then just stop before the fetch post request i.e. they don’t show any error regarding the request.

It’s working as expected locally, so curious where I might be going wrong for Netlify.

Help would be much appreciated. Main function file is below:

    'use strict';
    const express = require('express');
    const path = require('path');
    const serverless = require('serverless-http');
    const app = express();
    const bodyParser = require('body-parser');
    require('encoding');
    const fetch = require('node-fetch').default;

    const router = express.Router();

    app.use(bodyParser.json());

    router.post('/', (req, res, next) => {
        if (res.status(200)) {
          // Respond with the json data and success response
          console.log(`Success: ${JSON.stringify(req.body)}`)
          res.json({ postBody: req.body })
          res.status(200).end()
          next(); // Move on to next callback
        } else {
          console.log(`Error: data was not received`)
          res.status(400).end()
        }
    }, (req) => {
      console.log(`Next steps: post data with our token...`)
      // Store our body data in a var
      const jsonBodyData = JSON.stringify(req.body)
      
      // Get Token and make the Post Request
      getToken(VF_LOGIN_URL)
        .then(res => {
          console.log('Now lets do the post request')
          postData(VF_POST_URL, res)
            .then(postResponse => { console.log(`Success: ${postResponse.status} ${postResponse.statusText}`) })
            .catch(postError => console.log(`${postError} ${postError.message}`))
        })
        .catch(err => console.log(`${err} ${err.message}`))

      // Get the Token
      async function getToken(url) {
        const response = await fetch(url, {
          method: 'POST',
          body: `grant_type=client_credentials&client_id=${CLIENT_ID}&scope=${SCOPE}&client_secret=${CLIENT_SECRET}`,
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        })
        if (!response.ok) {
          const message = `An error has occured: ${response.status}`;
          throw new Error(message);
        }
        const data = await response.json();
        return data.access_token
      }
        
      // Post our request
      async function postData(url, token) {
        const response = await fetch(url, {
          method: 'POST',
          body: jsonBodyData,
          headers: {
            'Content-Type': 'application/json',
            'X-TrackingId': '123456',
            'Ocp-Apim-Subscription-Key': SUBSCRIPTION_KEY,
            'Authorization': `Bearer ${token}`
          }
        })
        if (!response.ok) {
          const message = `An error has occured: ${response.status} ${response.statusText}`;
          throw new Error(message);
        }
        return response
      }     
        
    });

    app.use('/.netlify/functions/server', router);  // path must route to lambda

    module.exports = app;
    module.exports.handler = serverless(app);

It looks like you have an if statement in your router.post function followed by a comma and then another function. That doesn’t look right to me. Also, you have a next() after logging the body. That skips the rest of your router.post callback.

I think you should put that anonymous function inside your if/else block instead of the way you have it.

Hi Dennis,

I’ve been looking back into this.
This is just using express multiple callbacks and that works in Netlify as well as local. So that doesn’t appear to be the issue.
e.g. Express routing

The process moves onto the second callback but the console logs stop before the first fetch post request. I have tried using axios and that’s not working either.

Extensive debugging of this, it just seems like Netlify functions can’t make outbound Post requests - it doesn’t even send back an error, the netlify function log just ends.

It seems like this is a similar issue: Netlify function post request to external server?

Is this the case? Is there any other way I can make this Post request with Netlify functions.

Appreciate the assistance.

Hi @danwebb,

Are you saying that you aren’t getting to console.log('Now lets do the post request')? Which exact console.log was the last one to work? Besides the multiple callbacks that I wasn’t familiar with, your code looks ok. I would suggest trying your code without multiple callbacks and see if that makes a difference.

Another thing to consider is that regular Netlify Functions have a 10 second runtime. Perhaps your function is running into that time limit?

Hi @danwebb, I have a similar issue, How have you fix it ?
thanks

Hi @bangaromaric, unfortunately I was pressed for time and I couldn’t get it to work via Netlify even after lots of debugging. I ended up switching to Heroku and it worked no problem first time.

Perhaps @Dennis can assist you further however.

1 Like

@danwebb thanks , I continue to search a soluce

Hey there, @bangaromaric :wave:

Thanks for reaching out. Sorry to hear you have encountered an issue. Can you please share:

  1. Your Netlify site name
  2. What you are trying to accomplish with functions
  3. What debugging steps you have tried
  4. Your function file

Thank you!

Hi @hillary :wave: , I hope you are well.

  1. My Ntelify site name : wallet241
  2. I tried to make a simple axios request, it work on local but after deploying on Netlify I get no response no error.
  3. Debugging step:
    • I tried to use fetch but that is same behavior
    • I tried to use node-libcurl and I get a error :

6:27:34 AM: 896f1fbc ERROR Invoke Error {“errorType”:“Error”,“errorMessage”:“Problem with the SSL CA cert (path? access rights?)”,“code”:77,“isCurlError”:true,“stack”:[“Error: Problem with the SSL CA cert (path? access rights?)”]}

However, I don’t use the custom domain

  • I search in this forum the similars issues and I found that this is my comment
  1. my Function file https://wallet241.netlify.app/.netlify/functions/send

thanks you

Hey there, @bangaromaric :wave:

Sorry for the slow response here, and thank you for your patience! We have been a bit under water the past two weeks.

Are you still experiencing issues with this? If so, can you please provide your github repo as well as any additional debugging steps you have taken? If you are not encountering issues, please let us know what steps you took to create a solution.

Thank you :slight_smile:

Hey @bangaromaric,
Finally got a chance to take a look and it looks like you’re now getting a new error + logging the function event and context, both great for debugging! For what it’s worth, the original error you were getting is straight from curl- error 77. Echoing @hillary, would love to know if you’re still running into it or have managed to move onto the next error?

1 Like