javascriptjsonfetch-apinetlifynetlify-function

Netlify Serverless Function returning 404


I am trying to set up a simple serverless function on Netlify just to test out usage of environment variables. I have defined the following two environment variables in Netlify for my site:

Variable Name Value
ALPHABET_SEPARATION 2
CHARS_BETWEEN 3

I have also updated my functions directory as follows:

Functions directory:           myfunctions

I am using continuous deployment from github. As I do not know the use of npm at present and finding it convenient to directly test the production deploy, I have defined a subdirectory called myfunctions inside my root directory and have placed my javascript file containing the "serverless" function inside it on my local machine. I have built in logic so that the "serverless" function gets called only when a "netlify" flag is set, otherwise, an alternate function gets executed client-side. Basically it works as follows:

const deploy = "netlify"  //Possible valid values are "local" and "netlify"

async function postRandomString() {
    const stringToUpdate = "THISISATESTSTRING"
    var stringToPost = "DUMMYINITIALVALUE";
    
    if (deploy === "local") {
        stringToPost = updateString(stringToUpdate); //updateString is a function defined elsewhere and executes client-side;
    }
    else if (deploy === "netlify") {

        const config = {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
            }
        };

        const res = await fetch(`myfunctions/serverUpdateString?input=${stringToUpdate}`, config);
        const data = await res.json();

        stringToPost = data.retVal;
        console.log(data.retVal);
    }
    else {
        stringToPost = "##ERROR##";
    }

    postString(stringToPost); //postString is a function defined elsewhere and executes client-side;
}

The serverless function file serverUpdateString.js is coded as follows (it basically sets a character at a certain position (determined by CHARS_BETWEEN) in the string to an alphabetical character which is a certain number (determined by ALPHABET_SEPARATION) of places in the alphabet after the first character of the string (don't ask why - the point is that it never even receives/handles the request):

exports.handler = async function (event) {
    const { CHARS_BETWEEN, ALPHABET_SEPARATION } = process.env;
    const charsBetween = CHARS_BETWEEN;
    const alphabetSeparation = ALPHABET_SEPARATION;
    const initString = event.queryStringParameters.input;

    const rootUnicode = initString.charCodeAt(0);
    const finalUnicode = "A".charCodeAt(0) + (rootUnicode - "A".charCodeAt(0) + alphabetSeparation) % 26;
    const finalChar = String.fromCharCode(finalUnicode);

    const stringArray = initString.split("");
    stringArray[charsBetween + 1] = finalChar;

    const stringToReturn = stringArray.join("");

    const response = {
        statusCode: 200,
        retVal: stringToReturn,
    }

    return JSON.stringify(response);
}

When I run it, I get a 404 error for the GET request: Error in Console Window - script.js:43 is the line const res = await fetch(myfunctions/serverUpdateString?input=ATESTSTRING, config);

In the above image, script.js:43 is the line const res = await fetch(myfunctions/serverUpdateString?input=ATESTSTRIN, config); in the calling file, as shown in the first code block above.

What am I doing incorrectly? Surely Netlify should be able to pick up the serverless function file given that I have specified the folder alright and have placed it at the right place in the directory structure? I have given the whole code for completeness but the problem seems quite elementary. Look forward to your help, thanks.


Solution

  • I got assistance from Netlify forums. Basically the following changes needed to be made:

    1. The fetch request -- line 43 in the calling code (script.js) -- needed to be changed to
    const res = await fetch(`https://netlifytestserverless.netlify.app/.netlify/functions/serverUpdateString?input=${stringToUpdate}`, config);
    
    1. The return statement in the lambda function needed to be changed to:
    const response = {
        statusCode: 200,
        body: JSON.stringify(stringToReturn),
        }
    
    1. Other minor changes such as using parseInt with the environment variables.

    The code works now.