by Naseer Ahmed Khan for NTU Open Source Society
This is the second workshop in the NTUOSS Web development workshop series. This workshop will build upon the beautiful front end developed in the first workshop. I highly recommend going through the first workshop here
The slides for this workshop can be found here
Artwork by Bryna Goh Jia Rui
When: Friday, 21 February 2020. 6:30PM - 8:30PM
Where: TCT-LT, Nanyang Technological University
Who: NTU Open Source Society
Please raise your hand any time during the workshop.
For errors, typos or suggestions, please do not hesitate to post an issue! Pull requests are very welcome, thank you!
- NTUOSS Web Backend Workshop
- Workshop Details
- Questions
- Errors
- Index
- Prerequisites
- Getting started
- Server code
- Simple Socket connection
- Server side code to establish a socket connection
- Client side code to establish socket connection
- Sending messages from client to server
- Recieving messages from client in the server
- Sending messages from server to client
- Recieving messages from server in client
- Broadcasting messages to all connected clients
- Setting up the group chat
- Setting up MongoDB
- Connecting to mongoDB from the server
- REST APIs
- Making REST API for MongoDB
- Deploying your server on Heroku
- Deploying your React app on github pages
- Simple Socket connection
- Nodejs
- Check if you have nodjs installed on your laptop by running the following command on terminal (Mac) or command line (windows)
node --version
- If you don't have it installed, get it here (for Windows users)
- Mac users can install brew by running
mkdir homebrew && curl -L https://github.com/Homebrew/brew/tarball/master | tar xz --strip 1 -C homebrew
- Then run
brew install node
- Postman
- If you don't have postman installed get it here
- A text editor
- Preferable Visual Studio Code because its amazing!
- Get it here
The first thing you need to do is clone this repository by running the following command on your terminal
git clone https://github.com/naseer2426/Backend-Workshop.git
If you don't have git installed you can download the zip of this repository here. Unzip this file and you will get a folder called Backend-Workshop. Open terminal/command-line in this folder.
Next, you need to enter the client folder by running the following command
cd workshop_code/client
Install all the dependencies required for the front end by running
npm install
After the installation is complete, run the following command to check if the front end works perfectly..
npm start
You should see something like this
Make a new folder called server inside the workshop_code folder. Enter this folder and open terminal here. Initialize node here by running the following command.
npm init -y
Install all the required dependencies by running
npm install --save body-parser cors express mongodb socket.io
Make a file named index.js, this will be your main file that runs your server code. Import all the dependencies into index.js
var express = require("express");
var app = express();
const bodyParser = require("body-parser");
const { MongoClient } = require("mongodb");
const PORT = 8000;
const cors = require("cors")({ origin: true });
var server = require("http").Server(app);
var io = require("socket.io")(server);
app.use(bodyParser.json());
app.use(cors);
A simple socket connection requires socket code on both client and server side.
io.on("connection", socket => {
console.log("connected new client");
console.log(socket.id);
});
server.listen(PORT, () => {
console.log(`Server listening to port ${PORT}`);
});
-
Importing socket.io
import io from "socket.io-client";
-
Assinging socket in the contructor
this.server = "http://localhost:8000"; this.socket = io(this.server);
Sending a JSON message to the server is the easiest thing the world.
this.socket.emit("send", newMessage);
socket.on("send", data => {
console.log(data);
});
socket.emit("recieving",data);
this.socket.on("recieving", data => {
console.log(data);
});
socket.broadcast.emit("recieving", data);
io.on("connection", socket => {
console.log("connected");
console.log(socket.id);
socket.on("send", data => {
socket.broadcast.emit("recieving", data);
});
});
server.listen(PORT, () => {
console.log(`Server listening to port ${PORT}`);
});
Sending a message to the server
var newMessage = {
body: this.state.message,
name: this.state.name
};
this.setState(prevState => ({messages: [...prevState.messages, newMessage],message: ""}));
this.socket.emit("send", newMessage);
Recieving a broadcast message from the server
this.socket.on("recieving", data => {
this.setState(prevState => ({
messages: [...prevState.messages, data]
}));
});
You would have noticed that all previous messages vanish when you reload the page. This is because we never save these messages anywhere. We need our own database to store our chats.
To set up mongoDB, click here and sign in with google. Once you sign in, you need to create a new project
Once the project is created, you'll see something like this.
Next you need to create an admin user whose credentials will be used to access the database. Go to database access under security and add user.
Next you need to white-list your IP address to access the database. For now we will just allow all IP addresses to access our database
Now you create a cluster for your database.
This is the server side code to connect to your MongoDB database.
const uri = //Enter your URI;
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
var messages;
client.connect(err => {
if (err != null) {
console.log(err);
}
messages = client.db("Telegram").collection("Chat");
console.log("Connected to mongo boi");
});
messages.find().toArray((err, docs) => {
console.log(docs);
});
var response = await messages.insertOne(req.body);
There are different types of HTTP requests (GET,PUT,UPDATE,DELETE,POST etc.). You can use express to call a function whenever the client sends an HTTP request to the server.
app.get("/", async (req, res) => {
//req has all the data sent by the client
//res has everything you need to send back a response
});
app.post("/send", async (req, res) => {
//req has all the data sent by the client
//req.body will give you the json body sent by the client
//res has everything you need to send back a response
});
First we need an API to get all the messages. We can use a GET request for this. The following code goes in the server
app.get("/", async (req, res) => {
messages.find().toArray((err, docs) => {
res.send(docs);
});
});
We can call this API from the client side using the following code.
fetch(this.server)
.then(res => res.json())
.then(
result => {
console.log(result);
},
error => {
console.log(error);
}
);
Next we make an API to add a mesasage to the database. This will be a POST request. The server side code is given below.
app.post("/send", async (req, res) => {
var response = await messages.insertOne(req.body);
res.send(response);
});
You can make the post request from the client side using the following code.
fetch(this.server + "/send", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(newMessage)
})
.then(res => res.json())
.then(result => {
console.log(result);
});
};
You can deploy your server online so that anyone in the world can access it. To learn how to deploy a node server onto heroku, you can follow this tutorial.
Since this is a static web page, you can deploy your front end in any server. I chose to do it on github pages. To learn how to do this follow this tutorial.