Setting up a basic Node-Express working Environment
- Create the Parent Directory.
- Run npm init : to create the package.json file.
- Run npm i express : to install express.
- Run npm install ejs : to install ejs (if running ejs files)
- Run npm install nodemon : to install nodemon (for build purposes)
- Create the "Server File" : index.js.
- Create a "Static Files Directory" and sub-directories (if needed)
- for any "static" files: imgs, pdfs, css, etc.
- Create a "views directory" (if needed)
- for your ejs files
- Create an "includes" directory" (if needed) : (sub-directory of views)
- for your include files such as header, footer, or css links
The subReddit Demo page has information on using arrays to set up multiple views directories, to support separate views pages that are not related.
Create a basic "Server File" (index.js)
- JavaScript
- index.js
- // Set the variables and requires
- const path = require('path');
- const express = require('express');
- const app = express();
- const port = 3000;
- assigning the port to a variable allows us to have one simple place to make changes, should we need to change the port number.
- // express middleware parser for post req.body
- app.use( 'express.urlencoded({ extended: true }))
- parser for application/x-www-form-urlencoded data
- app.use(express.json())
- parser for json data
- // set default views and path
- app.set('views', path.join(__dirname, 'views'))
- defines a path structure relative to THIS index.js file, to the "views" directory
- app.set('view engine', 'ejs')
- sets the default "view engine" to "ejs" files - allows us to eliminate the .ejs extension when routing to views
- // default get request format
- app.get( '/', ( req, res ) => {
- res.send('whatever you want sent from get req for processing');
- })
- // default post request format
- app.post( '/', ( req, res ) => {
- res.send('whatever you want sent from post req for processing');
- })
- // Start Server : Listening on { port }
- app.listen( port, () => {
- console.log(`Server Online : Listening on port: ${ port }`);
- });
With that, our server should now be available.
We start it by opening a Terminal window, and running node index.js or nodemon index.js (if nodemon is installed.). You should get the message, in the Terminal: "Server Online : Listening on port: 3000".
Open a browser window and go to: http://localhost:3000 to verify that the server is up and running.