How to Read User Data in Node.js

Create an HTML login form and use ExpressJS to set upwards the appropriate routes to navigate through the site and process the input.

Hypertext Transfer Protocol (HTTP) is the gear up of rules used for website communication. The customer and the server communicate with a asking and response structure. Routing ensures client-side requests receive the proper server response. The 2 types of requests used in this project are GET and Postal service.

The go method fetches data stored on the web server. A request is sent to the server when a user enters a specific URL (say heynode.com). The server will respond with the advisable web page data.

The mail service method updates or creates data. When a user submits a login class, they ship a request back to the server. In return, the server sends a response, such as the user's dashboard.

A route's path tells the server where data is located.

When a request is matched to the appropriate route, a function is executed. This function is called a handler. A road handler can contain one or more functions.

We are at present gear up to create the project.

Create login.html and index.html

Earlier nosotros get started on our JavaScript lawmaking, nosotros will make a uncomplicated HTML login course. If you are likewise responsible for the front-end code, you will probably want to pretty it upwardly with CSS and add validation or other forepart-end functionality. As is, the course beneath should exist enough to examination server-side functionality.

We will salvage the login form as static/login.html.

            <!DOCTYPE html> <html>   <head> 	<title>Example Login Class</title>   </head>   <body> 	<form action="//members.osiolabs.com/login" method="post">   	<!-- user input-->   	Username:<br>   	<input blazon="text" name="username" placeholder="Username" required><br><br>   	Password:<br>   	<input type="countersign" name="password" placeholder="Password" required><br><br>   	<!-- submit button -->   	<input type="submit" value="login"> 	</form>   </body> </html>                      

To demonstrate multiple GET routes, we will likewise create static/index.html. The index folio but contains a link to the login page:

            <!DOCTYPE html> <html>   <caput> 	<title>Welcome Home</title>   </head>   <body> . . <!-- link to login page--> 	<a href="/login">Delight Login Here!</a>   </body> </html>                      

Create a parcel.json file

Assuming you lot take already installed NodeJS, you are gear up to create your parcel.json file. Create it inside your primary project folder (login) by executing the post-obit command:

                          npm init -y                      

Install ExpressJS

While you lot are however in your primary project folder, install ExpressJS and dependencies.

            npm install express body-parser                      

Open up server.js

Now, we are set to work on our server code. Create a server.js and open up information technology in your editor so we can create our project's server.

Include ExpressJS

The commencement line in server.js will include the ExpressJS library.

            const express = require('limited'); // Include ExpressJS                      

Create an Express application

The second line in server.js will create an ExpressJS application.

            const app = express(); // Create an ExpressJS app                      

Include and apply body-parser

When a user fills out our login form, the information gets sent back to the server. The body-parser module is middleware that parses user input and makes it available through the req.torso property.

            const bodyParser = require('trunk-parser'); // middleware                      

And our application is going to utilise body-parser:

            app.use(bodyParser.urlencoded({ extended: false }));                      
  • .urlencoded indicates that we are parsing URL encoded data from the body. When working with forms, we employ the urlencoded parser because past default, forms send data in URL encoded format.
  • extended is an option allowing you to cull which library you want to utilise to parse the URL encoded data. By default, this option is set up to true and will use the qs library. When set to false, like the instance above, it uses the QueryString library.

Set routes for our GET requests

Let's offset with the road to our home page.

            // Route to Homepage app.get('/', (req, res) => {   res.sendFile(__dirname + '/static/index.html'); });                      

app.become is a office of:

  • Road Path: '/'
  • Route Handler:
    • A office of request (req) and response (res)
    • The server volition respond to the go request by sending the file '/static/index.html'

At present let'southward set up the login route.

            // Route to Login Page app.go('/login', (req, res) => {   res.sendFile(__dirname + '/static/login.html'); });                      

app.get is a function of:

  • Route Path: '/login'
  • Road Handler:
    • A function of request (req) and response (res)
    • The server will reply to the get request past sending the file '/static/login.html'

So far, server.js should look similar this:

            const limited = require('express'); // Include ExpressJS const app = limited(); // Create an ExpressJS app const bodyParser = require('body-parser'); // Middleware   app.use(bodyParser.urlencoded({ extended: imitation }));  // Route to Homepage app.get('/', (req, res) => {   res.sendFile(__dirname + '/static/alphabetize.html'); });  // Route to Login Folio app.become('/login', (req, res) => {   res.sendFile(__dirname + '/static/login.html'); });                      

Set up a route for POST requests

When a user submits the form, nosotros volition take to procedure the request. In a real-life awarding, the server would probably respond by serving that user their dashboard. In a later tutorial, we will write authentication code and do merely that. For this tutorial, nosotros will respond with the user's username and password.

            app.postal service('/login', (req, res) => {   // Insert Login Code Hither   let username = req.body.username;   permit password = req.body.countersign;   res.transport(`Username: ${username} Password: ${password}`); });                      

app.mail service is a function of:

  • Road Path: '/login'
  • Route Handler:
    • A function of request (req) and response (res)
    • The username input is stored in a variable called username and the password input is stored in a variable called password. When the form is submitted, we answer past showing the user their username and countersign.

Assign a port

Lastly, we will assign a port for our application to listen on. ExpressJS'southward app.listen role is based on NodeJS's http.Server.listen role.

            const port = 3000 // Port we will listen on  // Part to mind on the port app.listen(port, () => console.log(`This app is listening on port ${port}`));                      

Now server.js is complete and should look similar this:

            const express = require('limited'). // Include ExpressJS const app = express(). // Create an ExpressJS app const bodyParser = crave('torso-parser'); // Middleware  app.use(bodyParser.urlencoded({ extended: faux }));  // Route to Homepage app.become('/', (req, res) => {   res.sendFile(__dirname + '/static/index.html'); });  // Road to Login Page app.become('/login', (req, res) => {   res.sendFile(__dirname + '/static/login.html'); });  app.mail service('/login', (req, res) => {   // Insert Login Lawmaking Here   let username = req.body.username;   let countersign = req.trunk.password;   res.transport(`Username: ${username} Password: ${countersign}`); });  const port = 3000 // Port nosotros will heed on  // Function to listen on the port app.listen(port, () => console.log(`This app is listening on port ${port}`));                      

Kickoff the server

Open your local final and navigate to the principal project folder (login). Run server.js.

            node server.js                      

You should run across something like this in the terminal:

            candy@tuxie:~/Documents/login$ node server.js This app is listening on port 3000                      

Test the lawmaking

Finally, we are prepare to go to a web browser and test our code. Once in the web browser, navigate to: http://localhost:3000

You should see our dwelling page:

Express server home page with link that says &quot;Please login&quot;

Click on the link "Please Login Hither!" and navigate to the login page.

Login form with username and password fields.

Enter a username and countersign, so submit.

Login form with fields filled in.

Later submitting the form, you should see the username and countersign y'all entered displayed in the web browser.

ExpressJS is a NodeJS framework used to create spider web server software. Web servers route user requests to send back an appropriate response. A get request responds with data stored on the server and is commonly used to navigate a user to the appropriate web page. Mail service requests update existing data or create new data. They are frequently used to process user input.

ExpressJS routes are functions of a path and handler. The path is where the data is located, and the handler is a office of the client'southward request and the server's response.

guthriegothat.blogspot.com

Source: https://heynode.com/tutorial/process-user-login-form-expressjs/

0 Response to "How to Read User Data in Node.js"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel