0

I'm testing this on my linux localhost.

This is what I'm trying:

balter@spectre:/var/www/html$ cat .htaccess
Action cgi-node "/usr/bin/env node"
AddHandler cgi-node .js
balter@spectre:/var/www/html$ ls -al hello.js
-rwxr-xr-x 1 balter balter 99 Oct 31 13:17 hello.js
balter@spectre:/var/www/html$ cat hello.js
#!/usr/bin/env node

console.log("Content-Type: text/html");
console.log("hello from javascript");
balter@spectre:/var/www/html$ node hello.js
Content-Type: text/html
hello from javascript

When I visit localhost/hello.js all I see is the contents of hello.js

ADDITION I was wondering if I actually had cgi turned on. I figured I did because php worked. But I didn't have the cgi module enabled, or turned on in apache.conf.

So I added cgi.load and added to my apache.conf

###################################################################
#########     Adding capaility to run CGI-scripts #################
ServerName localhost
ScriptAlias /cgi-bin/ /var/www/cgi-bin/
Options +ExecCGI
AddHandler cgi-script .cgi .pl .py .js

Now, I get

Forbidden

You don't have permission to access /hello.js on this server. Apache/2.4.18 (Ubuntu) Server at localhost Port 80

Incidentally, same with an equivalent hello.py.

2
  • Testing your script with node hello.js is incorrect, you will need to try and execute the script i.e. see what happens when you execute /var/www/html/hello.js or ./hello.js- Also, for an administrator interpreting the generic error messages that are displayed in to a site visitor in their browser is frequently not nearly as useful as looking at the messages in the apache error log
    – HBruijn
    Nov 1 '17 at 8:25
  • Yeah, I talked to 1&1 and they won't let me see the apache error log :(. FWIW, the ls -al was to show that it is set to 755, and indeed does execute using the shebang.
    – abalter
    Nov 1 '17 at 14:46
0

I know this was asked almost 2 years ago, but just in case someone else lands here looking for a way to write a very simple CGI using node:

The Common Gateway Interface requires a blank line between the headers and content.

The example script above can be fixed by adding a \n to the end of the Content-Type header:

#!/usr/bin/env node

console.log("Content-Type: text/html\n");
console.log("hello from javascript");

Or by adding an empty console.log() between the headers and content:

#!/usr/bin/env node

console.log("Content-Type: text/html");
console.log();
console.log("hello from javascript");

These are both functionally equivalent, so it’s really a matter of personal style. #1 is microscopically more efficient, but not enough to recommend it if you find the explicitness of #2 easier to read.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.