In this step we’re going to create a node application that will function as our server
Navigate to the appropriate lesson_0x_file
in your class folder
Create a new folder named openweather-bot
Change directories into that folder
npm init
to bootstrap the Node applicationRun npm init
from the command line (make sure you inside your newly created project folder)
Accept all of the default values (just press “enter” at every prompt)
We’re going to be using Express, a minimal Node.js web framework, to quickly create our local server
In addition, we’ll also be adding other packages such as axios give our sever additional functionality
From the command line (inside your project folder) run the following command:
$ npm install express axios body-parser dotenv
package.json
contains the recently installed packagesOpen the project in your text editor and view the contents of package.json
Confirm that the content of the file looks similar to the following:
{
"name": "openweather-bot",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.19.0",
"body-parser": "^1.19.0",
"dotenv": "^8.1.0",
"express": "^4.17.1"
}
}
Let’s add some code to our server to get it up and running
Create a file named index.js
Next, add the following code to index.js
:
require('dotenv').config()
const express = require('express')
const bodyParser = require('body-parser')
const axios = require('axios')
// establishing the I/O port
const PORT = process.env.PORT || 3000
const app = express()
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(bodyParser.json())
app.listen(PORT, () => console.log(`App is up and running listening on port ${PORT}`))
app.get('/', async (req, res) => {
try {
res.json({ message: 'Welcome to Express Auth App!' })
} catch (e) {
res.status(e.status).json({ message: e.status })
}
})
In the code above, we are specifying that our server should run on port 3000 (const PORT = process.env.PORT || 3000
)
http://localhost:3000
app.get('/'...)
is what Express refers to as a route handler
The following code tells our server to return a welcome message (as json) for any successful requests sent to the root path (i.e. /
)
app.get('/', async (req, res) => {
try {
res.json({ message: 'Welcome to Express Auth App!' })
} catch (e) {
res.status(e.status).json({ message: e.status })
}
})
With servers, the root path represents host part of the url without anyting after the domain
For example the root path of CNN is https://cnn.com
(and not https://cnn.com/world
)
In our case, the root path of our local server http://localhost:3000
On the command line run the following command to run the server
$ node index.js
Open your browser and enter http://localhost:3000
into the address bar and press enter
The welcome message should be successfully displayed