A place to breathe

Friday, April 24, 2020

Express JS tutorial

Hello Developers

I would like to share how to build a Node JS backend server that is the simplest. It is called ExpressJS.

1. Download Node JS (https://nodejs.org/en/)
2. Make sure you have a command line. If you are on Windows, I recommend you use Git Bash
(https://git-scm.com/downloads)
3. Download your favorite editor (Visual Studio/Sublime, etc)
4. Download a command called "Curl"here https://curl.haxx.se/
5. Create a directory where you want your server to reside anywhere in your computer. with command line, you type "mkdir "
6. Go to your directory - "cd "
7. Now, if you've installed node correctly, you should be able to type "node" in your terminal. If you got an error, make sure that the Path is set correctly. You can set it either in your .bash_profile (Linux/Mac) or Environment variables (Windows)
8. Create initial node files by running "npm init"
9. Create a file called server.js "server.js"
10. Copy and paste the following code into server.js

const express = require('express');
const app = express();

app.get('/', (req, res) => {
res.send({
message: "hello, world"
});
});

app.listen(5000, () => console.log(`Node server listening to port ${5000}`));
 

11. Modify your package.json to use node script to run:

"main": "server.js",
"scripts": {
"start": "node server.js",
"test": "test"
},

12. Now, run your server : npm start
13. You can test your server by running curl command : "curl -X GET http://localhost:5000/"
$ curl -X GET http://localhost:5000/
{"message":"hello, world"}

Now you're done!. You can write your own API server from now on.
Good luck !

No comments:

About Me

I'm currently a software engineer. My specific interest is games and networking. I'm running software company called Nusantara Software.