Expressjs setup for html rendering — Self note series
This is another series of my self notes blog post. This is my journey of learning software development on the web. Based on many information I can get out there, I will then recorded here for my future reference(or maybe you too). Today I will talk about how to setup Express.js in a part of React.js app development.
Step 1
I will create a new folder and create basic package.json file
#in the terminal
$npm init --y
Step 2
I will create a folder called server and file named index.js. This is where the server setup will be coded. I will create a basic server setup to send simple ‘Hello React’ string.
#server/index.jsimport express from 'express';let app = express();app.get('/*', (req, res) => {
res.send('hello react');
});app.listen(3000, () => console.log('server started at localhost:3000'));
First the code import express from its module. Then it will setup the route for the string to be sent and finally it will listen on the port 3000 of the local host.
Step 3
In order for the server to run properly, I will need to install all the required module and setup some configuration
#terminal
$npm install --save-dev babel-cli
$npm install --save express
$npm install --save-dev babel-preset-es2015#.babelrc
{ "presets": ["es2015"]
}#package.json
"scripts": {
"server": "babel-node server/index.js",
},
Now if I run
$npm run server
and in browser I will go to localhost:3000, the word “hello react” will be rendered.
Final Step
I will make the server to serve index.html file. First I need to change the index.js file
#server/index.js
import express from 'express';
import path from 'path';let app = express();app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname, './index.html'));
});app.listen(3000, () => console.log('Running on a localhost:3000'));
Instead of sending a string now I will send a html file. In order to do this, I need to utilise the path method. Next we create the index.html file with any html markup.
#server/index.html
<h1>Hello World</h1>
Now if I run the server again, the index.html will be rendered accordingly.
Additional Step
I noticed that when a change was made in index.js the server need to be restart manually in order for the new change to take effect. This problem can be solved by using nodemon package.
#terminal
#npm install --save-dev nodemon#package.json
"scripts": {
"server": "nodemon --watch server --exec babel-node -- server/index.js",
},
So now nodeman will monitor for any changes in the folder server and will restart the server when saved.
Cheers, until next post.
notes: There are probably many ways to implement this feature and and this is how I find the easiest way for me to implement this. Anybody is free to give a comment for any mistakes or improvement that I can apply. This guide is initially for my own self to learn and remember about what I have done, nonetheless anybody is welcome to follow this guide if you find it is very helpful.