Nelify node-fetch 502 error

Hi,

I’m writing about a 502 error I’m receiving when calling my server less function. My Netlify function is using the node-fetch to get around CORS and I’m able to get a successful response when tested in my API tester (POSTMAN). It’s a POST request using Fetch.

The error thrown in the Netlify function console is

10:05:20 AM 2021-04-08T14:05:20.372Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Unexpected end of input","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Unexpected end of input","    at _loadUserApp (/var/runtime/UserFunction.js:98:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:999:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)","    at Module.load (internal/modules/cjs/loader.js:863:32)","    at Function.Module._load (internal/modules/cjs/loader.js:708:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}
10:05:20 AM 2021-04-08T14:05:20.587Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Unexpected end of input","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Unexpected end of input","    at _loadUserApp (/var/runtime/UserFunction.js:98:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:999:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)","    at Module.load (internal/modules/cjs/loader.js:863:32)","    at Function.Module._load (internal/modules/cjs/loader.js:708:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}
10:05:20 AM 108bca3f Duration: 168.66 ms	Memory Usage: 14 MB
10:05:20 AM Unknown application error occurred
Runtime.UserCodeSyntaxError

I believe it’s because of the way I call my function or handle the response within the function? I’m not sure that I’m handling the response correctly. My call from the front end looks like

 const sendData = () => {
fetch(`/.netlify/functions/sendData`)
  .then((res) => {
    console.log(res);
  })
  .then((result) => console.log(result));

};

And the function itself is

const fetch = require("node-fetch");

const handler = async function () {
console.log('in netlify function');
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Authorization", "Bearer **************************");

var raw = JSON.stringify({
  "table_name": "petition",
  "schema": {
    "properties": {
      "id": {
        "type": "integer"
      },
      "first_name": {
        "type": "string"
      },
      "last_name": {
        "type": "string"
      },
      "email": {
        "type": "string"
      },
      "cellphone_number": {
        "type": "string"
      },
      "zip_code": {
        "type": "string"
      }
    }
  },
  "messages": [
    {
      "action": "upsert",
      "sequence": 1565880010,
      "data": {
        "id": 3,
        "first_name": "Test",
        "last_name": "Testing",
        "email": "test@testing.com",
        "cellphone_number": "1234567891",
        "zip_code": "123456"
      }
    }
  ],
  "key_names": [
    "id"
  ]
});

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("https://api.stitchdata.com/v2/import/batch", requestOptions)
  .then(response => response.json())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

module.exports = { handler };

If you are able to spot any syntax errors or anything that would cause this please let me know. Thanks in advance for your help!

My site is hosted at [practical-hopper-ae0f7a.netlify.app].

Your function threw a couple of errors, I took the liberty of rewriting it. It’s untested, obviously, but at least it shouldn’t have any syntax errors:

const fetch = require("node-fetch");

exports.handler = async () => {

  let headers = new fetch.Headers();
  headers.append("Content-Type", "application/json");
  headers.append("Authorization", "Bearer **************************");


  const raw = JSON.stringify({
    "table_name": "petition",
    "schema": {
      "properties": {
        "id": {
          "type": "integer"
        },
        "first_name": {
          "type": "string"
        },
        "last_name": {
          "type": "string"
        },
        "email": {
          "type": "string"
        },
        "cellphone_number": {
          "type": "string"
        },
        "zip_code": {
          "type": "string"
        }
      }
    },
    "messages": [
      {
        "action": "upsert",
        "sequence": 1565880010,
        "data": {
          "id": 3,
          "first_name": "Test",
          "last_name": "Testing",
          "email": "test@testing.com",
          "cellphone_number": "1234567891",
          "zip_code": "123456"
        }
      }
    ],
    "key_names": [
      "id"
    ]
  });

  const requestOptions = {
    method: 'POST',
    headers: headers,
    body: raw,
    redirect: 'follow'
  };

  fetch("https://api.stitchdata.com/v2/import/batch", requestOptions)
    .then(response => response.json())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));
}

@tomrutgers Thank you very much for this.

1 Like

@tomrutgers Hi, I had another issue that is related to above and was hoping you can lend your eyes. When running locally using netlify dev in the cli, I call my serverless function in my front end follows…

  const sendData = () => {
fetch(`/.netlify/functions/sendData`, {
  method: "post",
  body: JSON.stringify(userData),
})
  .then((response) => {
    console.log(response.json());
  })
  .then((data) => console.log(data))
  .catch((err) => console.log(err));

};

My Netlify function reads

const fetch = require("node-fetch");
const parse = require("querystring");

exports.handler = async (event) => {
  let user = {};
  console.log(event.body, "in func");
  try {
    user = JSON.parse(event.body);
  } catch (e) {
    user = event.body;
  }

  console.log(user, "user object");

  let headers = new fetch.Headers();
  headers.append("Content-Type", "application/json");
  headers.append(
    "Authorization",
    "Bearer **********"
  );

  const raw = JSON.stringify({
    table_name: "petition",
    schema: {
      properties: {
        id: {
          type: "integer",
        },
        first_name: {
          type: "string",
        },
        last_name: {
          type: "string",
        },
        email: {
          type: "string",
        },
        cellphone_number: {
          type: "string",
        },
        zip_code: {
          type: "string",
        },
      },
    },
    messages: [
      {
        action: "upsert",
        sequence: 1565880011,
        data: {
          id: 10,
          first_name: user.first_name,
          last_name: user.last_name,
          email: user.email,
          cellphone_number: user.cellphone_number,
          zip_code: user.zip_code,
        },
      },
    ],
    key_names: ["id"],
  });

  const requestOptions = {
    method: "POST",
    headers: headers,
    body: raw,
    redirect: "follow",
  };

  fetch("https://api.stitchdata.com/v2/import/batch", requestOptions)
    .then((response) => response.json())
    .then((result) => console.log(result, "in sendData"))
    .catch((error) => console.log("error", error));
};

The response from the terminal is below, although the request is successful by verifying in the database UI.

◈ lambda response was undefined. check your function code again
Response with status 500 in 4 ms.
{ status: 'OK', message: 'Batch accepted' } in sendData

The issue here is when deployed to Netlify the serverless function doesn’t send the data to the endpoint, in addition, I get this error in the browser console

Promise {<rejected>: SyntaxError: Unexpected end of JSON input
    at https://petition.workmoney.org/static/js/main.ecea…}

VM8533:1 Uncaught (in promise) SyntaxError: Unexpected end of JSON input

Please advise if you might know what this issue is related to. Thanks in advance.

You’re using a try / catch block without any returns as if it’s an if statement. I’d get rid of that and try again.

1 Like