NodeJS Webservers

NodeJS Webservers sounds hard. And tutorials on Google are too. But it’s really simple.

The public folder

The first thing you need to do is create a public folder, and this is where you’ll store all of your frontend files (but do not put the index.js file here!).

To keep things simple, we’ll just create an index.html file in the public folder.

index.js code

const express = require("express") // Import the express module
const app = express() // Creates the web app

app.use(express.static("./public")) // Adds a middleware for serving static files to your app

app.listen(3000, () => {
  console.log("Server active!") // Listens on port 3000 and logs something if successful 
})

And it’s done! You can go to your website and see the index.html file in action.

Subdirectories also work. If you create a folder named subdir in public and put an index.html file in it, you can add /subdir to your website URL, and it’ll show the index.html file you put inside subdir.

404 pages

If you’ve entered a path or location that doesn’t exist in your website, for example mywebsite.com/nonexistent.html, it shows Cannot GET /nonexistent.html, which does not look good. But you can customize it!

Add a 404 folder in public, and add a 404.html file to it.

Add this code to your index.js file:

app.use((req, res) => {
  res.status(404).sendFile("index.html", { root: "./public/404" }) // When a 404 Not Found error is encountered, the server then sends the 404 file
})

And that’s it. It’s really simple.

If you found any errors in this resource feel free to edit it :smiley:

— OmegaOrbitals

4 Likes

Very nice. I would, however, include the ability to generate dynamic content, such as the “Hello World” example seen on most tutorials. This is a webSERVER after all…

2 Likes

What do you mean by “dynamic content”?

1 Like

I mean the ability to send content generated by some code at the server, for example see the Quote Generator:
https://flaskappexperiment.element1010.repl.co/python660

3 Likes

I intentionally avoided that. But if you really wanted to:

res.send("HTML code here")
3 Likes