Nginx and Node.js: A Powerful Web Server Combination

I've been searching for the solution for the past couple of days and I can't seem to figure it out. I have a node application that is utilizing socket io, residing in a subdomain which is nested under multiple folders

https://my.example.com/node/app1/
. Every time I navigate to the URL, I encounter this error message:
GET https://my.example.com/socket.io/socket.io.js
Uncaught ReferenceError: io is not defined

This is how my file structure looks like:

server {

        listen 443 ssl http2;
        server_name my.example.com;

        include /etc/nginx/include.d/ssl-common;
        include /etc/nginx/include.d/ssl-example;

        include /etc/nginx/include.d/all-common;

        root /var/example/my;

        location /node/app1/ {
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_http_version 1.1;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $host;
                proxy_pass http://localhost:3131;
        }

        location ~ \.php$ {
                fastcgi_pass unix:/var/run/ssl_example_com.sock;
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_intercept_errors on;
        }

        access_log /var/virdisoft/logs/access.log;
        error_log /var/virdisoft/logs/error.log;
}

app.js

var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(3131, function() {
  console.log('Listening on port 3131');
});

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

index.html

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io('http://localhost:3131');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

Answer №1

It seems like the error you're encountering is on the front-end. It's possible that the browser is searching for socket.io at

http://localhost/socket.io/socket.io.js
rather than
http://localhost/node/app1/socket.io/socket.io.js

To resolve this issue, make sure to import using a relative path:

<script src="socket.io/socket.io.js"></script>

Answer №2

To optimize your website, you should consider keeping the existing

<script src="/socket.io/socket.io.js"></script>
line and adding a new location directive specifically for socket.io. You can easily achieve this by inserting the code snippet below in your nginx configuration file:

location /socket.io {
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_http_version 1.1;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;
    proxy_pass http://localhost:3131;
}

Answer №3

After following the suggestions from everyone, I finally found a solution to my problem. I want to note that the domain: example.com is just a placeholder, so make sure to replace exmaple.com and my.example.com with your own domain name.

Here is the modified NGINX configuration:

upstream my_nodejs_server {
        server 127.0.0.1:3131;
}

server {

        listen 443 ssl http2;
        server_name my.example.com;

        include /etc/nginx/include.d/ssl-common;
        include /etc/nginx/include.d/ssl-example;

        include /etc/nginx/include.d/all-common;

        root /var/example/my;

        location ~ \.php$ {
                fastcgi_pass unix:/var/run/ssl_example_com.sock;
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_intercept_errors on;
        }


        location ^~ /node/app1/ {
                try_files $uri @my_nodejs_server;
        }

        location ^~ /socket.io/ {
                try_files $uri @my_nodejs_server;
        }

        location @my_nodejs_server {
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_http_version 1.1;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $host;
                proxy_pass http://my_nodejs_server;
        }


        access_log /var/example/logs/access.log;
        error_log /var/example/logs/error.log;
}

app.js

var fs = require('fs');
var app = require('http').createServer(handler);
var io = require('socket.io')(app);

app.listen(3131, function() {
  console.log('Listening on port 3131');
});

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

index.html

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing API routes within your React application

After creating my own API using nodejs, express and mongoDB, I successfully tested the routes with postman. However, I am struggling to integrate these routes into my react app for CRUD operations on the data. Despite having previous experience working wit ...

Windows npm configuration settings

After receiving helpful answers to my previous question about using a named parameter in an npm run script, I encountered a new problem. It seems that the $npm_config_variable doesn't function correctly on Windows OS. I am in search of a solution that ...

What are effective strategies to address compatibility issues with Vue 3 packages?

I'm currently facing an issue while attempting to update my npm packages. My aim is to integrate vue 3 into my project, but I'm encountering difficulties with the following 3 packages: @vue/composition-api vue-class-component vue-property-decora ...

Encountered an issue while trying to implement CORS using yarn

Currently experiencing the following issue: Error message: An unexpected error occurred "/home/vagrant/.cache/yarn/v1/npm-cors-2.8.4-2bd381f2eb201020105cd50ea59da63090694686/.yarn-metadata.json: Unexpected end of JSON input". Some important points to c ...

What is the reason Express Middleware fails to execute when placed after app.use(express.static(path.join(...)));

I am currently troubleshooting an issue in my straightforward express backend boilerplate. I have a universal middleware that should execute with each and every request hitting the server (specifically, I am aiming to establish a cookie). const express = ...

NPM Error: File Not Found

After attempting to check global modules, I encountered an ENOENT error. What could be causing this issue and how can it be prevented? https://i.stack.imgur.com/k9GaZ.png ...

The node sends a request to the API to retrieve data, which is then stored in an array. Subsequently, another request is

var UfcAPI = require('ufc-api'); var ufc = new UfcAPI({ version: '3' }); const fighterIdList = []; function fetchFighterIds() { ufc.fighters(function(err, res) { for (let i = 0; i < res.body.length; i++) { ...

Duplicate nodes_modules packages detected

Currently, I am utilizing npm to install numerous packages for my application. As a result, I have a node_modules directory that contains all the packages. However, some of these packages contain their own node_modules directories which in turn may contai ...

The challenge of obtaining a URL as a query string parameter in Node.js Express

What is the proper way to include a URL as a query string parameter in node.js? For example, if I were to access the browser with the following URL: http://localhost:3000/key1/https://www.google.com/key2/c, I am encountering difficulties retrieving value ...

Upon triggering a GET request to the URL "http://localhost:3000/search", a "404 (Not Found)" error response was received. Interestingly

Can Someone assist me please? I'm having trouble creating a website similar to YouTube and encountering the following error: GET http://localhost:3000/search 404 (Not Found) Uncaught (in promise) Error: Request failed with status code 404 at createEr ...

Attempting to gather information from a pair of inquiries

When attempting to retrieve data from two requests on two tables, I encountered some challenges in retrieving the expected results. My goal is to obtain a list of all elements included in each group within my dataset. This means acquiring all group IDs and ...

Issue encountered while establishing a connection between my React application and the Heroku server

I'm having trouble resolving an error that occurs when trying to connect my front-end React App with my Heroku server App. Whenever I send a request from the front-end, I encounter the following issue: Failed to load : No 'Access-Control-Allow ...

Encountering numerous issues during my attempt to perform an npm install command

After cloning a git repository, I encountered an issue when trying to run the app in the browser. Despite running "npm install," some dependencies were not fully installed. Upon attempting to run "npm install" again, the following errors were displayed: np ...

PassportJS is providing the `req.user` functionality to transmit all user information

Currently, I am utilizing PassportJS local strategy in order to authenticate users and it seems to be functioning properly. However, whenever I attempt to console.log(req.user) on any authenticated page, I can see all the database entry details of the user ...

The Ask CLI's integration with SMAPI through node.js is experiencing issues

Currently, I am attempting to retrieve some data metrics using the nodejs module for the ask-cli. Below is the command I used and the error message I received: ask smapi get-skill-metrics --skill-id amzn1.ask.skill.xxxxx --start-time 2020-10-14T12:45:00Z ...

Locating the specific file linked to a live Node.js process ID

Having recently set up a sophisticated enterprise application that utilizes Node.js to serve data, I find myself faced with the challenge of pinpointing the primary server file on a CentOS box. This application comprises multiple node.js applications runni ...

The module's return value is not defined

Hey there, I created a module and encountered an issue where the song name I'm trying to return is coming up as undefined. Oddly enough, the console.log just before it displays the correct values, so I'm a bit perplexed. The problem seems to be o ...

The installation of the executable in npm is set to be in usr/local/share/npm/bin instead of usr/local

After attempting to globally install npm serve, I encountered an issue when trying to run the serve executable. $ npm install -g serve Despite a seemingly successful installation, it appears that the serve command could not be found. It was discovered th ...

Setting up Webpack and Babel for ReactJS development

Recently, I started delving into the world of ReactJS and stumbled upon a tool called webpack which acts as a module bundler. However, I've hit a roadblock while configuring it and keep encountering the following error message: ERROR in ./src/index. ...

What are some reasons for the slow performance of AWS SQS?

My current project involves measuring the time it takes to send a message and receive it from an SQS queue. Surprisingly, the average time it takes is between 800-1200 ms, which seems like an excessively long period. Below is the code I have been using for ...