How To Setup An Express Server In Node.js


In this tutorial, we are learning how to install express js and start express server. You can use this code by copy-paste.

This tutorial shows you how to use the Express framework and Node.js to get a simple server setting up node.js server and running completely from scratch node js express tutorial.

How To Setup An Express Server In Node.js - PHP Coding Stuff
Important Terms Getting Started With Node.js

You will also need to have Node and npm installed.

To check if you have Node installed, open your terminal and run:

node -v


Then, To check if you have npm installed, open your terminal and run:

npm -v


With that out of the way, you can set up the project!

Set Up Your Project
mkdir express-tutorial


Then Create node express tutorials

npm init -y


This will create a package.json file and answer "yes" to all the questions because of the -y flag.

If you check out your package.json file, it should look similar to this:

{
  "name": "express-tutorial",
  "version": "1.0.0",
  "description": "This Tutorial PHP Coding Stuff",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "Robert Look",
  "license": "MIT"
}

This time if your package.json is not exactly the same, that is perfectly not fine setting up node.js server. You can add in the fields you want to make it match, but I will point out which fields you need to look out for as this file changes.

Then, we need to get set up express js, for now, is adding in the Express framework. Node express tutorials are the Node.js framework we will use to create the actual API endpoints, so we will need to install that Express package. To do that use:


npm i express


Running this command will add a few new files:

.
├── node_modules #new
├── package-lock.json #new
└── package.json
Creating The Initial Server

First, we want to create a file to store our main server code we learn setting up node.js server:

touch index.js


It is pretty standard to use index.js as the root file since this communicates to other express developers that this is where your application starts from node.js express tutorial.

From here you want to take whatever you name the file and type out:

const express = require("express");
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World! Welcome to phpcodingstuff.com')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

To test out the code, go back to the command line and run:

node index.js


If you've followed every step until now, you should see a message in your terminal saying:

Example app listening at http://localhost:3000


I hope it can help you...

Leave a Reply

Your privacy will not be published. Required fields are marked *

We'll share your Website Only Trusted.!!

close