Skip to content
← Back to Community
NodeJs Express tutorial
Profile icon
h
has Hacker Plan
PixelNinja

NodeJs Express Basics! YAY

Welp, I'm back! posting again, this time, I have got some web server basics. Even if you already know what Express is and how to use it, read along and maybe learn something!

Onto The Basics!

Installing!

First off, after creating your repl, you will want to install Express, if you create an Express repl, it will already be installed with a template. Otherwise, if you just clicked nodejs, you will need to install it, this can be done through 2 methods:

1)

Open shell (ctrl or cmd + shift + s)
Type in the shell: npm install express
Now you're ready to code!

2)

You can also auto-install it by just using require('express') which we will cover later!

Onto the main code...

You will need to import packages that we will be using. If you are editing on repl.it, packages will auto install, otherwise, please follow steps above for body-parser. Most editors will auto install packages when they are needed some won't so keep this in mind.

Sorry about all that boring stuff, onto the actual code, remember that all the code is at the bottom of the post!

Imports!

const express = require('express'); /* Imports the express library. This is necessary to have an express server. */ const bodyParser = require('body-parser'); // Node.js body parsing middleware.

Just some basic variable setting!

Creating the app / server

We need to turn our express into an app

const app = express(); ## Telling the app what modules / packages to use app.use(bodyParser.json()); // Express modules / packages app.use(bodyParser.urlencoded({ extended: true })); // Express modules / packages app.use(express.static('public')); // load the files that are in the public directory app.listen(3000, () => { // Listen on port 3000 console.log('Listening!') // Log when listen success })

Most of this stuff is standard for any express project!

Serving a file

To pick up when someone visits a directory we use app.get()

This will run when someone makes a get request to the url. We will cover other request types later. Here is an example:

app.get('/', (req, res) => { res.sendFile('/home/runner/public/index.html') })

When someone visits the root or / directory of the site, this function will run if it recieves a get request.

The req, res will let us use the request data and response data. res has lots of functions in which let us send headers to the client.

Here are some:

app.get('/res', (req, res) => { /* Please note that this will error as multiple headers are sent to the client */ res.send('Hello!') // or res.send('<p>Hello!</p>') res.json('{"hello":"hi","ping":"pong"}') res.sendStatus(200) //using res.send(200) is deprecated and will terminate the nodejs in future. res.sendFile('/home/runner/public/index.html') res.redirect('https://www.google.com') res.download('/home/runner/public/index.html') })

If you get an error about cannot send headers to the client after they are already sent this is because if you use 2 res functions then it will cause this error.

Using req

Query strings are the data included in the url and in the headers. these can be got server side, using req.query as showed below.

app.get('/req', (req, res) => { console.log(req.query) res.json(req.query) //send json to the client })

the console.log, logs all query strings such as '?hello=hi&ping=pong' you can get these through req.query.hello or req.query.ping.

res.json sends json to the client. often used in APIs.

Handling Request Types

There are many request types used for different things:

app.get('/get', (req, res) => { // On get request }) app.post('/post', (req, res) => { // On post request })

There are hundreds. Some can be found here
Only some are supported by express.

Handeling multiple methods is easy:

app.route('/reqtypes') .get(function (req, res) { res.send('Get') }) .post(function (req, res) { res.send('Post') }) .put(function (req, res) { res.send('Put') })

ez...

Long Paths

You can have multiple paths like this:

app.get('/multiple/paths', (req, res) => { // exist })

404

Make sure you put these at the bottom, as anything that isn't triggered, will run this:

app.get('/multiple/paths/also/work/*', (req, res) => { // used for 404 if no other get functions are triggered in this path }) app.get('/*', (req, res) => { // used for 404 if no other get functions are triggered })

Listening

When making a server, you need to get it to listen on a port so that the internet can go to your page! We do this with app.listen() and the port goes into the brackets. If you get any problems starting your repl, try changing the port.

Common ports are:

  • Port 80 for HTTP connections
  • Port 443 for HTTPS connections
  • Port 8080 is for other purposes

Repl.it normally blocks 2/3 digit ports but you can try anyways. Here is a bigger list: https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers

Outro

This has been just the basics but make sure you read other posts! Hope you enjoyed it!

Any questions feel free to ask!

Voters
Profile icon
LukeGF
Profile icon
OceanArbeit
Profile icon
SorenBlank
Profile icon
Marshalbravo
Profile icon
korrylol
Profile icon
emlbox
Profile icon
AtharvaPatil21
Profile icon
SEJINBAI
Profile icon
YouTube56
Profile icon
Venom373
Comments
hotnewtop
Profile icon
AaronActu

First of all, thanks for this tuto @RossJames ;)

I can't find how to access a route in my repl. For eg, I want to access the route: /mypath?info=somedatas. Is it possible with a REPL ?

Profile icon
PixelNinja

@AaronActu anything is possible with replit! Yes, you can use if statements to check req.query (get question mark data, msg any problems

Profile icon
Shadow-Runner

Really helpful def recommend this for any beginners

Profile icon
sanjaykuma

anjan

Profile icon
gksrlf2ek

Thanks for the tutorial! However I am having some trouble using replit. I can see that the code you uploaded works well and server is working. But when I do it on my repl, it doesn't work. Even though it says started, the URL doesn't respond. I checked wheter server gets request, and I found that server even doesn't get request.

Profile icon
PixelNinja

@gksrlf2ek Hi! Is this still an issue? It could have been a temporary outage

Profile icon
gksrlf2ek

@PixelNinja :D It works now haha.. Thanks!

Profile icon
jeremybradbury

There's no way to navigate to /error /res etc... the browser only allows base urls, no params, nothing. I don't understand how anyone can make express routes work, other than the index route.

Profile icon
PixelNinja

@jeremybradbury Hi! app.use(express.static("public")) makes the public directory open. Anything in that is pushed to the root url.

Profile icon
jeremybradbury

@PixelNinja no I mean the browser frame on replit dot com, it doesn't allow you to add any paths or query params, just use the base index route.

You have to use another tab just so you can edit the url at all... seems kinda silly. Is that a feature or a bug?

Profile icon
BeezerButt

Found the solution (even though the GET is hard coded at least you get a response...you can then try to add the routes using the above example):

var http = require('http') , https = require('https') , express = require('express') , app = express(); http.createServer(app).listen(80); app.get('/', function (req, res) { res.header('Content-type', 'text/html'); return res.end('<h1>Hello, Shot World World!</h1>'); });

and wget works in the console. :=)

you can configure a module for routing if you go to the bottom of this page:
https://expressjs.com/en/guide/routing.html

Take the [birds] example router, implement it, and then in the [console] use wget:
wget https://[YOUR REPL DETAILS].repl.co/birds

Profile icon
BeezerButt

Thanks for the tutorial.
Not working because of:

  1. 3000 port number will not work
  2. Replacing it with 80 or 8080 does not throw an error message, but it is still https and not http
  3. doing a curl to the URL for my replit project just hangs

Any, chance you can shed some light on these issues.

thanks in advance.

Update 1: I tried with curl and the flags to ignore certificate checking and it just hangs.
I tried with wget and a connection is made, and you see the IP address and everything, BUT, it then just waits for the response.
It would be very helpful for the tutorial, therefore to know how to make the REPL listen on http rather than https.

update 2: looks like you can specify the type of server that express will listen on (http vs. https) however it is not entirely clear, if REPLIT will intervene.
I am investigating...

Profile icon
PixelNinja

@BeezerButt hi, port 3000 does work as all my active projects use it. I'm not too sure what these errors are, but i believe it could be a config error. If you do not specify a port, it will choose a suitable one for you. Hope this helps

Profile icon
Dunce

Hello, I'm having trouble getting this to work. It's not giving me an option to visit my website, and if I type in the URL manually it gets stuck on "repl waking up..."
Here's my code

Profile icon
PixelNinja

Hey @Dunce !

I see the problem. I forgot to add that you need to get the server to listen!

Add this code at the bottom:

app.listen(3000, () => { console.log('Listening!') })

Edit: I have also added this to the guide

Profile icon
Dunce

@PixelNinja Okay, thanks a lot!

Profile icon
Highwayman

Yay indeed! Thanks for this.