Creating a server with node js
a) custom server creation
1. Set Up Your Project
First, you'll need to create a new directory for your project and navigate into it:
shellmkdir my-node-servercd my-node-server
Then, initialize a new Node.js project:
shellnpm init -y
2. Install Required Packages
You'll need to install the express package, which is a popular framework for building web servers in Node.js and nodemon a popular tool in Node.js development that monitors your project files for any changes and automatically restarts the server when it detects updates. This feature is extremely useful during development, as it speeds up the process by eliminating the need to manually stop and restart the server every time you make a change to your code:
shellnpm install express nodemon
3. Create your server file
javascriptconst express = require('express');const app = express();const port = 3000;app.get('/', (req, res) => {res.send('Hello, World!');});app.listen(port, () => {console.log(`Server is running on http://localhost:${port}`);});
b) Using Express application generator
Use the application generator tool, express-generator, to quickly create an application skeleton.
You can run the application generator with the npx command (available in Node.js 8.2.0).
shellnpx express-generator
For earlier Node versions, install the application generator as a global npm package and then launch it:
shell$ npm install -g express-generator$ express
Basic routing
Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).
Each route can have one or more handler functions, which are executed when the route is matched.
Route definition takes the following structure:
javascriptapp.METHOD(PATH, HANDLER)
Where:
appis an instance ofexpress.METHODis an HTTP request method, in lowercase.PATHis a path on the server.HANDLERis the function executed when the route is matched.
javascriptapp.get('/about', (req, res) => {res.send('About Us');});app.get('/contact', (req, res) => {res.send('Contact Us');});
handling post requests
To handle POST requests, you can use the app.post() method. You'll also need to add middleware to parse the request body:
javascriptapp.use(express.json());app.post('/submit', (req, res) => {const data = req.body;res.send(`Data received: ${JSON.stringify(data)}`);});
Serving static files in express
To serve static files such as images, CSS files, and JavaScript files, use the express.static middleware:
javascriptapp.use(express.static('public'));
Implementation
set up an index.js
javascriptconst express = require('express');const bodyParser = require('body-parser');// Initialize Express appconst app = express();// Middleware to parse JSON requestsapp.use(bodyParser.json());// Sample users array (for example purposes)const users = [{ id: 1, name: 'John Doe' },{ id: 2, name: 'Jane Smith' },{ id: 3, name: 'Mike Brown' }];//get usersapp.get('/users', (req, res) => {res.send(users);});// Get a user by ID// Create a user routeapp.post('/users', (req, res) => {const user = req.body; // Get user details from the request body// Check if user exists (basic validation)if (!user.name || !user.email) {return res.status(400).send('Name and Email are required');}// Add user to the arrayusers.push(user);// Send responseres.status(201).send({ message: 'User created successfully', user });});// Start the serverconst PORT = 3005;app.listen(PORT, () => {console.log(Server is running on port ${PORT});});
this implements but store the relevant data in an array, users post data to the /users endpoint and the data is temporarily stored in an array which is used to validate the user
Implementation using mongo db
setup a server.js
javascriptconst express = require('express');const bodyParser = require('body-parser');const mongoose = require('mongoose'); // Import mongoose// Initialize Express appconst app = express();// Middleware to parse JSON requestsapp.use(bodyParser.json());// MongoDB connection stringconst mongoURI = process.env.CONNECTION_STRING; // Replace with your actual MongoDB URI// Connect to MongoDBmongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }).then(() => console.log('MongoDB connected...')).catch(err => console.error('MongoDB connection error:', err));// Define a Mongoose Schema for Usersconst userSchema = new mongoose.Schema({name: {type: String,required: true},email: {type: String,required: true}});// Create a Mongoose model for Usersconst User = mongoose.model('User', userSchema);// Sample users array (for example purposes)const users = [{ id: 1, name: 'John Doe' },{ id: 2, name: 'Jane Smith' },{ id: 3, name: 'Mike Brown' }];// Get all usersapp.get('/users', async (req, res) => {try {const users = await User.find(); // Fetch users from MongoDBres.send(users);} catch (err) {res.status(500).send('Error fetching users');}});// Create a user routeapp.post('/users', async (req, res) => {const { name, email } = req.body;// Validate request bodyif (!name || !email) {return res.status(400).send('Name and Email are required');}try {// Create a new user and save to MongoDBconst newUser = new User({ name, email });await newUser.save();res.status(201).send({ message: 'User created successfully', user: newUser });} catch (err) {res.status(500).send('Error creating user');}});// Start the serverconst PORT = 3005;app.listen(PORT, () => {console.log(Server is running on port ${PORT});});
Implementation with mongo db for user management and authentication with jwt
Espress contact_backend with authentication
Go to the below and clone the repo:
setup a .env
javascriptCONNECTION_STRING =PORT = 3000ACCESS_TOKEN_SECRET =
Run this in the terminal to generate ACCESS_TOKEN_SECRET
shellnode -e "console.log(require('crypto').randomBytes(64).toString('hex'))"oropenssl rand -base64 64
then:
shellnpm install && npm run dev
