Overview
This article will show how to create and run a super simple Express server using Node.js within an Angular App.
Setup
Create A Sandbox App
With the Angular CLI installed, run
ng new
. This will ask for some options to initialize the angular app. Once the options have been supplied and the command has finished running,
into the newly created app and open it into a code editor.
#### npm installs
These are the packages you'll need to install from npm:
- express
- express-session
- dotenv
#### Creating .env File
In the root folder of the project, create a file named '.env'. Environment variables will be placed here and then called from the index.js file. This isn't necessary to create the server, but it is likely that more sensitive environment variables will be needed when creating endpoints and calling API's from the server. **It is also important that this file be added to the .gitignore file.**
The two environment variables needed are:
```.env
// .env
SERVER_PORT=<serverPortToRunOn>
Creating The Express Server
In the root folder of the project, create a new folder called "Server". Inside that folder create an "index.js" file. This is the file where the server will live and run from. In the index.js file add these lines of code:
// index.js
const express = require("express")
const app = express()
var session = require("express-session")
require("dotenv").config()
Now in index.js get access the variables that were created in the .env file,
then add the code for the actual server:
// index.js
const { SERVER_PORT } = process.env;
app.listen(SERVER_PORT, () => {
console.log(`Server listening on port: ${SERVER_PORT}`)
});
That's it! All that is left to do now is to run
node server/index.js
in the terminal from the root folder. If everything was done correctly,
Server listening on port: 4000
should display in the terminal.
Top comments (1)
Really explains everything in detail, the article is very interesting and effective. wazifa to make impossible possible in one day