blakyan / node-express-course Goto Github PK
View Code? Open in Web Editor NEWAn introduction to Node.js and Express.js servers
Home Page: https://lab.github.com/everydeveloper/introduction-to-node-with-express
An introduction to Node.js and Express.js servers
Home Page: https://lab.github.com/everydeveloper/introduction-to-node-with-express
Alright, now let's start making a server! Open up your server.js file and add these two lines:
const express = require('express');
const app = express();
The first line gives you access to the express library by searching your node_modules for "express". The next creates an instance of the express constructor, which we will name "app".
We can now access methods used for making a server by including their name after app. Add this to the bottom of server.js:
app.listen(8000,function(){
console.log("server is running")
})
The app.listen method will start up the server locally on the port you give as its first argument (in this case the base url is: http://localhost:8000)
But first we need to run the server.js file by entering this in the terminal: node server.js
If everything was successful, you should see the console.log message we supplied in the callback: "server is running". This happens because the file is being run on our terminal. To end this process, push CTRL+C. Whenever you make changes to your server, you need exit and restart it.
Once your server is working, push your changes up to GitHub to complete this step.
git add server.js
git commit -m"set up express server"
git push origin master
In Express, words with a colon in front of them in the url are treated as variables. You can access the value of each variable through req.params, like this:
app.get('/users/:id',function(req,res){
console.log(req.params.id)
res.json({
success: true,
message: 'got one user',
user: req.params.id
})
})
Let's test it out!
Add the function above your app.listen
function in your server.js file, restart the server, and paste this into your browser url: http://localhost:8000/users/mark
Now check the terminal for the console.log of req.params.id. You should see the name 'mark', since it is the value we passed in place of the 'id' variable. Since we are running this in the terminal, our console.log will appear there (instead of the browser).
After testing that it works, push your changes your GitHub repo:
git add server.js
git commit -m"add dynamic GET route"
git push origin master
First, let's install Node.js, and an app called Postman to test our API. You will be coding along with me, so make sure you also have git installed.
Node.js comes with something called NPM (Node Package Manager) that we will use manage our node modules. You can check if you have Node, NPM, and Git installed by running these commands (one at a time):
node -v
npm -v
git --version
You should get a version back from each of these commands. If you get an error, you'll want to check that it was correctly installed.
By signing up for this course, a template repository was created on your GitHub account. Clone this repository locally on your computer and navigate to it by running:
git clone https://github.com/Blakyan/node-express-course.git
cd node-express-server-intro
Open the folder you just cloned in your favorite text editor.
You should have a few files already created:
.gitignore
server.js
The server file will be the main one we use. In the .gitignore folder, you should see this line at the top /node_modules
Express (the server library we will install) is a node_module. Rather than track the entire library in our git history, we will create a package.json file, which will allow us to install and save node modules.
Run this from your command line: npm init -y
You should have a package.json file in your folder now.
Now you can install Express using NPM. Enter this command in the terminal: npm install express --save
A folder called node_modules should apear in your project. This is where the actual files for express are stored. If you open the folder, you can see how many files there are. These will only be stored on your machine, because we told git to ignore this entire directory.
In your package.json file and make sure you have something like this under your dependencies:
"dependencies": {
"express": "^4.17.1",
}
The number on the right is the version you downloaded. Since we aren't tracking the actual node_modules
folder, this section is a reference used to re-install the modules your application depends on.
When you are finished with this section, push your file to GitHub for the next step:
git add .
git commit -m "initial file setup"
git push origin master
_Congratulations!_๐๐๐
You finished the course. You can now make a basic JSON server using Express and NodeJS! You're kind of like a wizard! ๐ง But you have only scratched the surface.
The best place to see what's possible with Express is on its official website.
If you want to...
Of course, Express is only one way to use Node...
To see the many other applications for Node, visit its official documentation.
If you want to...
There are also many Node examples on GitHub to learn from!
Now it's time to go make something! ๐
Leave a comment below with what you want to build, as a note to yourself!
So far, we have only made GET requests to our server. A POST request can send data securely through the request body. In order to make POST requests, first we need to include the "body-parser" library from our node_modules (included with express). Add these lines after the app variable:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
Let's write a function to handle a POST request made to the 'login' endpoint, as if a user was trying to log in:
app.post('/login',function(req,res){
const username=req.body.username;
const password=req.body.password;
const mockUsername="billyTheKid";
const mockPassword="superSecret";
if (username===mockUsername && password===mockPassword){
res.json({
success: true,
message: 'password and username match!',
token: 'encrypted token goes here'
})
} else {
res.json({
success: false,
message: 'password and username do not match'
})
}
})
Your entire file should look like this now:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json())
const mockUserData=[
{name:'Mark'},
{name:'Jill'}
]
app.get('/users',function(req,res){
res.json({
success: true,
message: 'successfully got users. Nice!',
users: mockUserData
})
})
// colons are used as variables that be viewed in the params
app.get('/users/:id',function(req,res){
console.log(req.params.id)
res.json({
success: true,
message: 'got one user',
user: req.params.id
})
})
app.post('/login',function(req,res){
// Typically passwords are encrypted using something like bcrypt before sending to database
const username=req.body.username;
const password=req.body.password;
// This should come from the database
const mockUsername="billyTheKid";
const mockPassword="superSecret";
if (username===mockUsername && password===mockPassword){
// In practice, use JSON web token sign method here to make an encrypted token
res.json({
success: true,
message: 'password and username match!',
token: 'encrypted token goes here'
})
} else {
res.json({
success: false,
message: 'password and username do not match'
})
}
})
app.listen(8000,function(){console.log('server is listening')})
Time to commit our changes!
git add server.js
git commit -m"add login POST route"
git push origin master
Traditionally, JavaScript is a browser-side programming language. However, Node.js gives you the ability to run JavaScript files on the server-side. Express is a library for Node.js, that allows you to make requests to different "endpoints" and get a response back.
In this tutorial you will learn how to:
When you see the ๐ก symbol, the following info is a optional tip, or context.
This tutorial is interactive. Look for instructions on how to complete each step at the bottom of the issue. If the next step doesn't appear, try refreshing the page.
When you are ready to start, close this issue.
Now that our server is listening for requests being made on localhost:8000 let's return some mock JSON data. Add the following to your server.js file:
const mockUserData=[
{name:'Mark'},
{name:'Jill'}
]
app.get('/users', function(req,res){
res.json({
success: true,
message: 'successfully got users. Nice!',
users: mockUserData
})
})
Overall your file should look like this:
const express = require('express');
const app = express();
const mockUserData=[
{name:'Mark'},
{name:'Jill'}
]
app.get('/users',function(req,res){
res.json({
success: true,
message: 'successfully got users. Nice!',
users: mockUserData
})
})
app.listen(8000,function(){console.log('server is listening')})
Let's save your changes on GitHub:
git add server.js
git commit -m"add first GET route"
git push origin master
We can make GET requests all day through the browser url, but to make a POST request, we need to get more sophisticated! Open up the PostMan App, and look for an input field that says: "Enter Request Url". It is between a dropdown menu and a Send button.
First, change the dropdown on the upper left from GET to POST. Next, enter our login url next to the dropdown (http://localhost:8000/login). Before you hit send, we need to change a few things.
Click the "Headers" tab, and enter the key: Content-Type. In the box just to the right, enter the value: application/json. This tells the server the request is going to be in JSON format.
Next, click on the "Body" tab. In the dropdown below, change the value to "raw", and enter the login data below:
{
"username":"billyTheKid",
"password":"superSecret"
}
Restart your server, to make sure you have the latest version running (with body-parser and our post function). Click send in PostMan, and you should get a positive response from the server.
When you get a response, close this issue for the next step.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.