Create a folder and start an NPM project in the terminal,
npm init
It will show a prompt to add the project details. After finishing all details, it will create the package.json
file.
Note: If you want to create a
package.json
file with the default configuration, then you need to runnpm init -y
.
Add express
package into the project,
npm install --save express
or the shortcut version,
npm i -S express
Create server.js
file in the root directory. And add the code for hello world,
// Require Express Js const express = require('express'); // Create an App using Express const app = express(); const port = 8080; // Add a route for the root URL - i.e, `/` app.get('/', (req, res) => { // Send a string - Hello World! res.send('Hello World!'); }); // Server will listen to port - 8080 app.listen(port, () => { console.log(`App listening at http://localhost:${port}`); });
Now run the server using the node server.js
command. It will run the server on port 8080
.
Open the server at http://localhost:8080. It will display the Hello World!
string.
What happens in the server.js
file?
We used the express
JS framework to create a simple web app listening at port 8080
. It sends the string Hello World!
if we accessed the URL through the browser.
Codesandbox playground will help you to try the code example by trying yourself. But I encourage you to try coding along with the course if you want your learning to stick around you for a long time.
We have used express Js, a node Js framework for the course. But the concept of REST API design will be common for any language or framework.