Serverless Function Returning 404 Error

Hey everyone. I am new to Netlify (and web development) and require help with use of Netlify functions along with environmental variables. I am writing this after checking out a lot of YouTube tutorials, Netlify documentation/support guides (e.g. this and this and other documentation along with posting on Stack Overflow here, and I am asking for support here in the hope of getting it to work.

My relevant URL is Netlify Environment Variables Test. It is designed just to test out use of environmental variables and serverless functions on Netlify. I am not making use of any Netlify CLI or NPM at my local machine, and am relying on a flag in my code to deploy and test directly on production. I’m doing it way because (a) I don’t know how to use NPM (b) It is a simple test (c) It will help me learn something about how Netlify functions work.

So, 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(, config);

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

What am I doing incorrectly? If I understand correctly, 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, correct? I have given the whole code for completeness although the problem itself seems quite elementary.

Look forward to your help, thanks.

No matter what you specify as the functions folder, once deployed, they are always available at https://www.domain.com/.netify/functions/functionName/.

1 Like

Thanks a lot for your answer. I changed my fetch call to the following:

const res = await fetch(`https://netlifytestserverless.netlify.app/.netlify/functions/serverUpdateString?=${stringToUpdate}`, config);

This seems to have resolved the original issue but now I am getting a 502 response instead on the fetch call, as seen below:

Could you offer any clues please regarding what might be amiss this time? Thanks.

You’re returning a response in the wrong manner. It’s done like this:

return {
  statusCode: 200
  body: JSON.stringify(stringToReturn)
}
3 Likes

You’re right, that needed to be changed and I have fixed it now.

My code is now working thanks to your assistance. Your help is much appreciated.

1 Like