Server
1) Create a project directory
mkdir basics
1) Initialize the project using npm init.
cd basics
npm init
2) Since we'll be using express as our backend, let's install it using npm. Also, since we'll have our client and server in the same project folder, let's install concurrently too. We'll use it later though.
npm install express concurrently
3) Create a server directory in project root folder and then create a server.js inside it. Add the below code in server.js to do basic server setup.
const express=require('express');
const app=express();
const PORT=process.env.PORT || 5000;
app.listen(PORT, ()=>{
console.log(`Server is running on ${PORT}` )
})
4) Verify the server setup.
node ./server/server.js
5) Now let's get to a bit advanced stuff, not advanced in the real sense but since we're talking from a beginners prespective, everytime, you do any changes to your server, you need to restart it, so let's install nodemon to get rid of that.
npm install nodemon
One important thing to note here is if nodemon is not installed globally, the below command may throw an error.
nodemon ./server/server.js
zsh: command not found: nodemon
The reason is that you need to install it globally by using the command
su npm install --g nodemon
else you may use the npx keyword to run it.
npx nodemon ./server/server.js
Client
1) Create a client directory in the project root
mkdir client
2) Navigate to the client directory and create a react application by using the below command. Note that, since we don't want to create a new folder inside client folder, we use dot operator.
npx create-react-app .
You may test your client by running the below command
npm start
Refactoring
If you notice, you have three different commands to start you server and client.
node ./server/server.js
nodemon ./server/server.js
npm start
Let's just add all these commands within the scripts of package.json. So, let's open package.json and add the below
"start": "node ./server/server.js",
"server": "nodemon ./server/server.js",
"client": "npm start --prefix client",
Now let's make use of concurrent package we installed earlier. Add a dev script inside scripts and add the below content.
"dev": "concurrently \"npm run server\" \"npm run client\"",
Now stop all previously run server and start both server and client using
npm run dev
Now, since my client is running on http://localhost:3000 and server on http://localhost:5000 , let's add a proxy in the client side so that everytime it makes a request to server, we don't have to explicitly type the whole url. Open package.json inside the client folder and add
"proxy":"http://localhost/5000"
This is my first blog people, do leave your feedback and any improvement areas if need. I would love to hear from you.
Top comments (0)