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