Search code examples
javascripthtmlnginxfastcgi

Javascript undefined function on a page served by FastCGI


I have a simple HTML form that is handled by embedded javascript functions that does all calculations locally.

<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
</head>
<body style="background-color:#ffccee;">

<form>
    <input id="firstThing"> <br><br>
    <button type="button" onclick="return doThings();">click me</button><br><br>
</form>
<script>
    function doThings(){...}
</script>
</body></html>

Once I serve the page using FastCGI through Nginx, the buttons' onclick actions become broken.

Uncaught ReferenceError: doThings is not defined
onclick https://page.com/app.o:1

It's clear that the page is trying to contact my CGI app, but my intention is to get the button to run the embedded javascripts. What setting do I have to change?

# NGINX config
http {
    include       mime.types;
    default_type  application/octet-stream;
    charset       utf-8;
    sendfile        on;

    server {
        listen       443 ssl;
        server_name  page.com;
        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
            #some fastcgi_param removed...
            if ($uri !~ "^/assets/") {
                fastcgi_pass 127.0.0.1:1234;
            }
        }
    }
}

Solution

    1. Move the javascript functions in the html to its own file (assets/script.js in this example).

    2. Change the script tag in the html to reflect the change:

        <script type="text/javascript" src="assets/script.js"></script>
    

    The actual script path in the html will depend on your Nginx config. Since my server is set to bypass CGI and serve the contents of the assets folder as-is, we are done here.

    My button is now working correctly. The onclick action is handled by the javascript source instead of the CGI.