NodeJS Express
ExpressJS
Express JS is a Node.js framework designed to build APIs that facilitate communication through HTTP requests and responses. One of the remarkable things about Express is that it gives developers complete control over the requests and responses that are associated with each of its app’s methods.
Let's start writing code and initializing the JavaScript project.
- Create a
New Terminal
-
Run
npm init
in your terminal for initializing your JavaScript project -
After you run the
npm init
command, it will ask you about thepackage name
which is the name of your project. (if you don't want to name your project you just pressenter
to skip, and it will name the project as a name that you see in the parenthesis).- In the
version
, you can specify the version of the project, If you don't want to specify the version, you just pressEnter
to skip this, it will set version 1.0.0 as default. 👇🏻
- The
description
is just a description of your project, If you don't want to add a description, you just pressEnter
to skip this. 👇🏻
- The
entry point
is the file from which execution starts. It depends on the project configuration and run time environment of the technology we are using. - Examples: For a node.js project
index.js
is used to initialize the app and glue everything together.
- For the entry point, we will use
index.js
file as a main file, pressEnter
to skip this, and use theindex.js
as a default. 👆🏻 - Skip the
test command
👇🏻
- For the
git repository
, you just leave it blank.
- For the
keywords
, you just leave it blank.
- The
licence
, you just leave it blank, the default will be an ISC license.
- After that, it will show the data in the package.json file that shows the information of the project that you have filled in the command line.
- Press
Enter
to create a JavaScript project.
- After that, you will see the
package.json
file that has been created after you create a JavaScript project.
Let's write a simple hello world API using ExpressJS
- Install the
ExpressJS
framework to your project, by enter the command linenpm install express
-
After you installed the express framework to your projec, you will see the
package.json
has been updated, its add thedependencies
object to the file. -
dependencies
is the object that contains version of the module of yourframework
,library
that you use in your project. 👇🏻
{ "name": "simple_express", "version": "1.0.0", "description": "Simple ExpressJS project", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "express": "^4.18.2" } }
3. Write the following code
- In the
- Check it's Work Go to Browser search localhost:3000
5. Try to add more route by implement with data.json
-
- Check Result localhost:3000/banks
What you see ?
- You will see that if that path is the same, the backend application will send the data correctly.
- Check Result localhost:3000/banks