Trying to use netlify functions with form data

Hi there i am trying to create a serverless function that get a form data to create a .md file on Github

i used axios to fetch through an api the data, am unable to use the data for the following steps.

map.hoopers.club

thanks in advance

Hi @hoopersclub,

Could you share the stuff you’ve tried till now? We can take it from there.

Hi, @hrishikesh. Thanks in advance for trying to help out.

I’m using axios to get the data. I am able to see the data in that console.log. But when I try to pass it through stringify it returns an empty object.

exports.handler = async function (event, context) {
	
	const axios = require('axios');

	const response = await axios({
		method: 'get',
		url: '*****',
		params: {},
	});

	const data = await response;
	console.log(data);

	return {
		statusCode: 200,
		body: JSON.stringify({ message: 'Hello World!' }),
		body: JSON.stringify(data),
	};
};

I tried multiple ways and it either returns empty object or timeout error.

Do you have any idea what I might be doing wrong?

I wonder why would you need 2 body in the return statement.

In any case, you should probably use promises for less error-prone code. For example, you should convert the above to:

const axios = require('axios')
exports.handler = async function () {
  return axios({
    method: 'get',
    url: '*****',
    params: {},
  }).then(({data}) => {
    return {
      statusCode: 200,
      body: JSON.stringify(data)
    }
  })
}

Personally, this syntax gives me a clear understanding of what’s waiting for what and how the data is being sent to the next function call.

2 Likes

Works like a charm. Thank you @hrishikesh :pray:

1 Like