Setting up an NGINX server to route requests to a node server without a specified path

I have a server running Nginx with the following setup:

server
{
    listen 80;
    server_name example.ca www.example.ca;
    location / {

proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}

On the Node server, I am listening on port 3000 using Node Express as follows;

app.get('*', function (req, res) {
  console.log('Request received ', req.headers.host);
});

I also have a domain www.example.com pointing to the IP of the Nginx server. The tests I am conducting are:

http://www.example.com/test result ===> Request received www.example.com

http://www.example.com/test/abc result ===> Request received www.example.com

http://www.example.com result ===> (I get no result !! It's like the app.get did not trigger)

Can anyone help me with this issue? When I visit the domain without any path parameter, I'm not receiving any result. It seems like Nginx is not forwarding this request to the node server!!

Answer №1

When accessing abc.com through a browser or using curl, the path will always be sent as /. It is not possible to send a blank path.

Your nginx configuration seems to be set up for a socket.io implementation and should look like this:

server
{
    listen 80;
    server_name example.ca www.example.ca;
    location / {
       proxy_pass http://127.0.0.1:3000;
       proxy_http_version 1.1;
       proxy_set_header Host $host;
    }
}

If you are not ending your requests properly, they may time out. Make sure your code looks like this:

app.get('*', function (req, res) {
  console.log(' request received ', req.headers.host);
  res.status(200).send("all ok");
});

For troubleshooting purposes, you can use curl like so:

curl -v http://www.example.com

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

NPM - Include in package.json without installation

Can a command be executed to validate that the package is a legitimate npm package, include it as a dependency in package.json, but refrain from actually installing it? This question arises from the need to utilize a specific package globally and incorpor ...

Repetitive NodeJS event triggers within Electron-React application causing unexpected behavior

In my custom software package (referred to as PACKAGE_A), I have implemented various automated tasks using a node script. This package includes a Notifier module that creates and exports an EventEmitter. (The entire project is structured as a Monorepo) co ...

What is the true purpose behind the existence of package-lock.json and shrinkwrap?

First and foremost, I want to clarify that I am well aware of the technicalities behind package.json, package-lock.json, and npm shrinkwrap. These concepts are extensively covered on various platforms online. My curiosity lies in understanding the rationa ...

I am currently in the process of verifying email addresses

I attempted to validate multiple email addresses from a txt file and then save the valid emails to another txt file using nodejs. Unfortunately, it did not work as expected. Despite successfully reading the file, all emails were deemed invalid, even though ...

Exploring the power of Mongoose geolocation queries

I currently have a collection of documents stored in MongoDB with the following structure: { "_id": "5839f170ca31803284785ef3", "name": "Alex", "coordinates": { "type": "point", "coordinates": [ -23.073889, ...

The fetch() POST request is met with an error message stating "415 Unsupported Media Type"

I keep encountering a 415 error when attempting to upload a PDF file using fetch(). The PDF file resides in the same directory as the js file, and the name is correct. async function uploadFile(filePath, extension, timestamp) { const url = "https ...

JavaScript encounters a parsing error when dealing with an async function

Ever since I developed a node.js web application, I've been utilizing MSSQL for the database. To streamline SQL functions, I crafted functions (sql.js) to handle all the necessary queries. Furthermore, I set up async function handlers (controllers.js) ...

Is it possible to exclude certain static files from being served in express.static?

const express = require('express'); const app = express(); app.use('/app', express.static(path.resolve(__dirname, './app'), { maxage: '600s' })) app.listen(9292, function(err){ if (err) console.log(err); ...

The property is returning an empty string, but the function is functioning perfectly

Check out this related Stack Overflow post exports.getAddress = asyncHandler(async (req, res, next) => { var lon = req.query.lon; var lat = req.query.lat; var formattedAddress = ""; var url1 = 'url' request(url1 ...

Encountering "environment.prod.ts path does not exist in file replacements" error while Dockerizing Angular build

I am encountering an issue with a Dockerfile that throws an error during the build process. I attempted to install the angular/cli globally and run ng build --prod using a separate RUN command, but the same error persists. Dockerfile FROM node:12.17.0-al ...

What are the specific purposes of utilizing semantic versioning (semver) notation within the package.json file?

Could someone clarify the specific distinctions between the semver notations found in package.json file? I'd appreciate a detailed explanation. ...

Module-alias cannot be resolved by esm

Currently, I am utilizing the combination of esm package and module-alias. However, it appears that esm is not recognizing module-alias's paths. This is how I am loading my server file: nodemon -r esm ./src/index.js 8081 At the beginning of my inde ...

Removing a specific MongoDB document by its ID within an Express.js application

I am at my wit's end with this...struggling to remove a document by its id: router.delete('/api/menu/delete/:id', function (req, res) { var id = req.params.id; db.get().collection('menu', function (err, col) { col.deleteOne ...

Creating a system for admin approval of blog posts in a node.js and express application

I recently developed a Blog application using Node.js, Express, and MongoDB. In order to maintain quality content on the site, I am now looking to implement a system where a designated admin must approve each user's post before it can be published. M ...

Tips for extracting and mapping a sub array from the category response JSON using SWR with MongoDB in a Next.js (Node.js) environment

Can anyone assist me with reading and mapping arrays inside JSON? Using Hook (useSWR / useCategories): import useSWR from "swr" const fetcher = (...args) => fetch(...args).then(res => res.json()) function useCategories () { const { data, erro ...

Totally at a standstill. (Problem with MongoDB in my MERN stack)

Currently developing an app, focusing on a feature that takes user input and stores it in the database. Although I've implemented this in past projects, I'm facing a persistent issue. Upon user input submission, the data is sent to the backend w ...

Having trouble with mongoose-paginate and react using material-ui's TablePagination component? Encountering issues where the second page onwards does not render after

I am still learning my way around React, and I believe there is a crucial component missing in this particular React setup. Any assistance leading to a solution will be greatly appreciated. The Functionality I'm Striving For Here - I aim to incorpora ...

Strategies for resolving the nodejs $lte endpoint variable issue

I've been working on a mean stack project where both the front end and back end work perfectly in isolation. However, when I try to connect them together, an error arises that I can't seem to trace. The error pops up in the nodejs terminal whenev ...

Deployment failure due to undetected development keys in gitignore

I have a TypeScript-coded Express server with three files for keys in the compiled and pre-compiled code: /// dev.ts - development keys const keys = { googleClientSecret: "GOOGLE_KEY", mongoURI: "mongodb+srv://MONGO_K ...

FirebaseCloudMessaging : PlatformException (PlatformException(null-error, The host platform unexpectedly returned a null value for a non-null return value., null, null))

I am currently facing a challenge in sending notifications from a Node.js API to a Flutter application. Initially, my goal is to enable my application to receive notifications from Firebase. However, I encountered an issue when initializing the app: Pla ...