Coding our server

It's time to create our FIFA backend folder and start working on the API development. Open your Terminal and run the following command:

$ mkdir wc-backend
$ cd wc-backend
$ npm init -y

{
"name": "wc-backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}

Once the initialization is done, let's install Express.js. Execute the following command:

$ npm install --save express

Next, create the server.js file in the root folder and write the following code:

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

app.use((req, res) => {
res.send("Hello!")
})

app.listen(3000, () => {
console.log('running on port: 3000')
})

We start importing the express module and instantiation of an express application into the app variable. Next, we use the application instance to configure a simple request handler using the app.use function. Into this function, we pass another function as a parameter that has two parameters for the request and response: req and res. To send a simple message, we use the res parameter.

Once the server application instance is configured, we bring it to life by calling its listen function and passing the HTTP port where it will listen to new HTTP requests:

$ node server.js
We strongly recommend you to use nodemon in development. The nodemon will restart your node application every time it detects a change in your source code automatically. To install nodemon, just execute the npm install -g nodemon command. To run your server, use the nodemon server.js command.

Let's test it by opening http://localhost:3000 in your browser or using an HTTP client command-line tool. Consider the given example:

$ curl http://localhost:3000

Hello!

So far so good! Let's define a route path to make a self-explanatory API. Apply the following change to the server.js file:

...
app.use('/hello', (req, res) => {
res.send("Hello!")
})
...

Now, head over to http://localhost:3000/hello and you should see the same Hello! message. You can navigate to http://localhost:3000 to see what you get after the change:

$ curl http://localhost:3000/hello

Hello!
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset