POST request using netlify functions and axios. POST works, but I get a status 500 error and the response isn't returned

Hi, I am trying to get a post request working using netlify functions, i’ve looked at the existing topics, but haven’t managed to find a solution within any of them.

I am mostly confused because the POST is working… and the console logs the response, but it just isn’t making it back to my actual app.

My functions file looks as follows:


const axios = require("axios");

exports.handler = async function (event, context) {

    console.log(event);
    console.log(context);

    let baseURL = "https://solana-mainnet.g.alchemy.com/v2/MYENDPOINT";

    let config = {
    timeout: 1000,
    headers: {'Content-Type': 'application/json'}
    };

  
    var data = {"id": 1, "jsonrpc": "2.0", "method": "getAccountInfo", "params": ["4NGT1Us38TFbxgQXkHizgefFA9HLgNFHLMkHNnnbXSPZ"]};

    axios.post(baseURL, data, config)
    .then((res) => {
      console.log("RESPONSE RECEIVED: ", res.data);
      return {
        statusCode: 200,
        body: JSON.stringify({ title: "this was a success" }),
      };
    })
    .catch((err) => {
      console.log("AXIOS ERROR: ", err);

      return {
        statusCode: 404,
        body: err.toString(),
      };
    });
};

And in my app i am doing:

 const url = `/.netlify/functions/todo`;
        try {
            const todo = await fetch(url);//.then((res) => res.json());
            console.log(todo);

        } catch (err) {
            console.log(err);
    }

However in the browser console i see the following:

GET http://localhost:8888/.netlify/functions/todo?id=1 500 (Internal Server Error)

and on the netlify console i see:
◈ lambda response was undefined. check your function code again

and yet directly below that :

RESPONSE RECEIVED:  {
  jsonrpc: '2.0',
  result: {
    context: { apiVersion: '1.13.5', slot: 164055495 },
    value: {
      data: 'hfBSZujcLcTnoGenk1EfKKSWEttMWSuniCjGLbYzWqtbgmjP3CPQXrwAynW7G7DmadESwc2xMc2NSCqEeUETzcjcVjcDMjx2pXLgZhv8h2hPV',
      executable: false,
      lamports: 1447680,
      owner: 'GwsxvpsHURySgnLrkMcnYuSH2Sbd4v9eZwB5ruiVxgjE',
      rentEpoch: 361
    }
  },
  id: 1
}

So clearly the post request is being sent, i’m getting a response, and the response is what I expect, but for some reason the function is throwing an error expecting a GET when it is actually a POST…

Any help would be appreciated!!

Try changing that to return axios.post()...

1 Like