Basic 'express-less' Node Server - HTTP calls
Hello people.
This is a comprehensive post to learn javascript, for those people who have got stuck in the front-end, and haven't been able to experience much of the server side, and crave to look inside the obscure console.
This is for complete beginners who have never coded or have been limited to only writing front end code but want to start understanding the javascript fuelling it. All the git commits are attached along with the subtopics.
Those who have a basic knowledge of javascript can just skim through the introductory sections and jump straight to the following sections.
I will skim through the list of topics we will be covering.
What setup will you need
Installing Node
package.json
https server
Make your own small server
url query
Installing new dependencies
Let's build a small application
Summary
I break apart everything in the parallel world of materials that exists around me to be able to understand it in the form of logic that applies the same way in code.
What setup will you need.
You will need to run this on your local machine and would be required to have the following set up -
- Terminal / Command prompt
- Text Editor - Popular examples - MS code, sublime or you could use a vim editor
Clone the following repository to get started right away. Use your terminal/command prompt and run the command git clone https://github.com/sagarmunjal/simple-node-app.git
. It’s and empty repository and we will be building everything from scratch.
To get started on how to clone a repository click here.
git clone https://github.com/sagarmunjal/simple-node-app.git
Installing Node
Next we download the laterst version according to your OS from the link below.
https://nodejs.org/en/
Once you install node, you can cross verify whether it is installed or not by executing the following commands in your terminal / command prompt.
node -v
npm -v
This should return something like this
Node comes with few basic configuration commands as follows -
npm init
Initialises a Node.js application and creates a package.json file
npm install <package>.
Installs a Node.js package.
npm publish
Saves and uploads a package you built to the npm package community.
npm start
Runs your Node.js application (provided the package.json file is set up to use this command).
npm stop
will quit the running application.
package.json
package.json
is the file where all basic configuration setting is stored. We can either create it using the command npm init
or manually make a package.json
.
In the following steps we would be writing our own package.json. The following instructions will load node
as your project dependency.
To get started follow the instructions -
- First ensure you are in the current project directory and run the following command in the terminal/command prompt.
- Make a new file named
package.json
- copy the following code to
package.json
{
"name": "simple-node-application",
"version": "1.0.0",
"description": "A small node application",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"node": "10.10.0"
},
"keywords": []
}
- Run the command
npm install
in your terminal.
https server
This section covers some basic functions of the http module
a Node.js library of code used for handling requests over the internet. Through a few short steps, you’ll convert a few lines of JavaScript into a server with which you can communicate on your web browser.
The most basic http methods
are GET
and POST
GET
This method is used to request information from a server. Typically, a server responds with content you can view back on your browser (e.g. clicking a link to see the home page of a site).
POST
This method is used to send information to the server. A server may respond with an HTML page or redirect you to another page in the application after processing your data (e.g. filling out and submitting a sign-up form).
Make your own small server
See all the previous changes here and follow the instructions below to run a server locally.
- Create a new file called
index.js
this will be the entry file for our javascript server. - Copy the following code in
index.js
const http = require('http');
const app = http.createServer((request,response) => {
console.log('server is running...')
})
app.listen(3000);
- Run the command
npm start
- Open the page
localhost:3000
Once you open the page you will notice that the webpage does not load but the message gets successfully logged into the terminal server is running...
which means our index.js
file works.
Let’s understand what we did in the instructions and created the most basic server.
We first imported the http
module by const http = require('http’);. We store the reference object thats returned by the method
createServer()into a variable
app. In the following section, we play around with the two parameters we pass to
createServermethod.
reqand
resare two arguments passed to the
serverobject. Lastly, we use the method
listento start the server.
listen(/* port number */)is passed a port number on which the server will be running. The website can be accessed at
localhost:3000`.
url query
Change the index.js
file to the following -
const http = require('http');
const url = require('url');
const app = http.createServer((request,response) => {
var querystring
querystring = url.parse(request.url,true).query;
if (querystring) {
response.writeHead(200, {"Content-Type": "text/html"});
console.log('the index.js has loaded')
response.write(`<h1>The parsed value from the url is ${querystring.value}</h1>`);
response.end();
}
else {
response.write(`<h1>No values were passed</h1>`);
response.end();
}
})
app.listen(3000);
Restart your node server.
Go to the url
http://localhost:3000/?value=xenobia
You will be able to see the value printed in the html.
Let's understand what we did in the code above.
In the above example we import the new http
module which helps us to parse url queries.
Lets try to output the value passed through the url query on our main page.
We import the url
module and store it in the url
variable. Later, inside the app function we use the url.parse
method, a function to parse and store the object. Value returned from url.parse(request.url,true).query
is stored in a variable querystring
.
Later we can access the value using querystring.value
.
loading new module
We change the index.js
to the following and create a new file module.js
. Update the index.js and module.js`
/* index.js */
const http = require('http');
const url = require('url');
const newModule = require('./module.js');
const app = http.createServer((request,response) => {
var querystring
querystring = url.parse(request.url,true).query;
if (querystring.value) {
response.writeHead(200, {"Content-Type": "text/html"});
console.log('the index.js has loaded')
response.write(`<h1>The parsed value from the url is ${querystring.value}</h1>`);
response.end();
}
else {
response.write(`<h1>No values were passed check your terminal/command prompt for log message.</h1>`);
newModule.addlog();
response.end();
}
})
app.listen(3000);
/* module.js */
exports.addlog = () => {
console.log(` module.js has loaded`)
}
Restart your server.
Go to localhost:3000/
. You will see the terminal with the log message module.js has loaded
.
Installing new dependencies
Dependencies are javascript modules which can be downloaded to your project. npm install --save node
. Then you can import the dependencies in your project using const moduleName = require(/* package name /*);
Throughout your development with Node.js, you’ll hear the terms module and package thrown around a lot. Here’s what you need to know:
Modules are individual JavaScript files containing code that pertains to a single concept, functionality, or library.
Packages may contain multiple modules or a single module. Packages are used to group together files offering relevant tools.
NOTE: “Dependencies” are Node.js modules used by an application or another module.
Use the following command to install a new npm module cities
.
Open your terminal and run the following command.
npm i --save "cities"
.
Now you will notice that your package.json
has a new dependency added to it.
{
"name": "simple-node-application",
"version": "1.0.0",
"description": "A small node application",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"cities": "^1.1.2",
"node": "10.10.0"
},
"keywords": []
}
Let's build a small application
In the following app we would be passing the zip code of a city using the query parameter and then display the name of the city on the screen.
Replace the contents of module.js
and copy the following contents.
/* module.js */
const cities = require('cities');
exports.addlog = () => {
console.log(` module.js has loaded`)
var myCity = cities.zip_lookup(10016);
console.log(myCity);
}
Restart your server.
Head on to localhost:3000
and you will notice the following value logged into the terminal.
{
zipcode: ’10016’,
state_abbr: ’NY’,
latitude: ’40.746180’,
longitude: ’-73.97759’,
city: ’New York’,
state: ’New York’
}
Next we will fetch and use the above data using the querystring value. In the module.js file we will define a new function findcityname(zip)
. The function accepts an argument zip
and returns the city name.
Open module.js
and copy the following code.
const cities = require('cities');
exports.findcityname = (zip) => {
return cities.zip_lookup(zip).city;
}
exports.addlog = () => {
console.log(` module.js has loaded`)
}
We need to fix the index.js file in order to parse the zipcode from the uri. So change the index.js
to the following code.
const http = require('http');
const url = require('url');
const newModule = require('./module.js');
const app = http.createServer((request,response) => {
var querystring,zip;
querystring = url.parse(request.url,true).query;
zip = querystring.value
if (zip) {
response.writeHead(200, {"Content-Type": "text/html"});
console.log('the index.js has loaded')
response.write(`<h1>${querystring.value} is the zip code for ${newModule.findcityname(zip)} <br> </h1>`);
response.end();
}
else {
response.write(`<h1>No values were passed check your terminal/command prompt for log message.</h1>`);
newModule.addlog();
response.end();
}
})
app.listen(3000);
Restart your server.
Head to localhost:3000/?value=10016
Now, you would be able to see the following outpout.
Summary
The code can be created more interactive and I would be updating any later versions of this blog coming out here in the summary section.
Challenge -
User could search for a city name using the zip code.
For that we will need to add an input
field and a search button
to our front end. When the user enters the zip code and presses the search button it should either result in a successful or an unsuccessful result.