In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what is the get/post request method in nodejs". In the daily operation, I believe that many people have doubts about what the get/post request method in nodejs is. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "what is the get/post request method in nodejs?" Next, please follow the editor to study!
1. Node hot restart
1. Installation
Npm i nodemon
two。 Run and start
Nodemon .bin / www
II. About the get request
Generally, in website development, get is used for data acquisition and query, which is similar to the query operation in the database. When the server parses the foreground resources, the corresponding content is transmitted. The query string is carried out on the URL, such as:
Http://localhost:8080/login?goods1=0001&goods2=0002
Get the foreground get request
The get request sent by the user can be obtained through req.query, and then the corresponding data is returned to the user through the node operation.
If you send:
Http://localhost:8080/login?goods1=0001&goods2=0002
The response is through:
Req.query
He will get all the data, or
Req.query.goods1req.query.goods2
Come individually or go to each data. In short, different needs correspond to different businesses, and we can get them according to our own needs.
Example
Here is an example to summarize the acquisition of get parameters:
HTML:
Users:
Password:
Node:
Const express = require ("express"); var app = express (); app.get ("/", function (req,res) {res.send ("home page");}); app.get ("/ login", function (req,res) {console.log (req.query); res.send ("login route, user is:" + req.query.user+ "= > password is" + req.query.password);}); app.listen (8080); III. About POST request
As an important part of http request, post method is useful to almost all websites. Unlike get, post request is more like a modification operation on the server, and it is generally used to update data resources. The data requested by post is more secure than get requests. In the previous chapter, we found that the get request will display the user name and password entered in the address bar (if there is Chinese, it will be converted to BASE64 encryption), while the post request will put the data into the body of the http package, which makes it impossible for others to see the user name and password directly!
How does Express set up POST requests
1. First of all, we need to know that when we make a post request in the form form, the enctype property is generally set to "application/x-www-form-urlencoded". If set to multipart/form-data, it is mostly used for file upload, as follows:
two。 Set up parsing body middleware
App.use (express.urlencoded ())
3. Get body data
Req.body.username login case:
HTML:
Document login user name: password: login
APP.JS
Var express = require ('express'); var path = require (' path') var app = express (); var sqlQuery = require ('. / lcMysql') / / view engine setupapp.set ('views', path.join (_ _ dirname,' views')); app.set ('view engine',' ejs'); app.use (path.join (_ dirname, 'public')) / / parse the data submitted by post app.use (express.urlencoded ()) / / search the home page app.get ('/', (req,res) = > {res.render ('index.ejs')}) / / the landing page app.get (' / login', (req,res) = > {res.render ('login')}) / / process the login request app.post (' / login',async (req) Res) = > {/ / get the username and password let username = req.body.username let password = req.body.password / / query whether the database has this username and password let sqlStr = 'select * password =? And password =?'; let arr = [username,password]; let result = await sqlQuery (sqlStr,arr) if (result.length = = 0) {res.send ("login failure")} else {res.send ("login success")}} module.exports = app; IV, middleware
From the literal meaning, we can see that it is probably doing the intermediate proxy operation, and this is also the case; in most cases, the middleware is doing a series of operations between receiving the request and sending the response. In fact, express is a routing and middleware web framework, and Express applications are basically calls to a series of middleware functions.
1. Browser sends request
2.express accepts request
Intermediate processing process
3. Routing function handles rendering (req,res)
4.res.render rendering
Middleware functions can perform the following tasks:
Execute any code.
Make changes to the request and response objects.
End the request / response cycle.
Call the next middleware function in the stack.
Middleware is also divided into application layer middleware, routing middleware, built-in middleware, error handling middleware and third-party middleware. The following are explained respectively:
1. Application layer middleware
Application-level intermediate keys are bound to app objects using app.use and app.METHOD ()-methods that need to handle http requests, such as GET, PUT, POST, just replace the previous get or post with use. For example, the following example:
Const express=require ("express"); var app=express (); / / actions before matching routes app.use (function (req,res,next ()) {console.log (before access);}); app.get ("/", function (req,res) {res.send ("homepage");}); app.listen (8080)
At this point, we will find that the http://localhost:8080/ address has been loading, but the command line shows "before access", indicating that the program will not be executed synchronously. If you use next to continue to match down routes, then you can get the home page data again:
Const express=require ("express"); var app=express (); / / actions before matching routes app.use (function (req,res,next) {console.log (before access); next ();}); app.get ("/", function (req,res) {res.send ("homepage");}); app.listen (8080)
Of course, it can also be simplified:
Const express=require ("express"); var app=express (); app.use (function (req,res,next) {console.log (before visit); next ();}, function (req,res) {res.send ("homepage");}); app.listen (8080)
Therefore, the application layer middleware is undoubtedly a good choice if you want to do something before the route matching or when you want to continue to execute down again.
two。 Routing middleware
Route-level middleware is similar to application-level middleware, except that it needs to bind express.Router ()
Var router = express.Router ()
When matching routes, we use router.use () or router.VERB (). Routing middleware combined with multiple callback can be used for user login and user status detection.
Const express = require ("express"); var app = express (); var router=express.Router (); router.use ("/", function (req,res,next) {console.log (before match); next ();}); router.use ("/ user", function (req,res,next) {console.log ("match address:", req.originalUrl); next ();}, function (req,res) {res.send ("user login");}) App.use ("/", router); app.listen (8080)
In short, routing middleware is absolutely easy to use in detecting which page the user should log in and guide the user to visit.
3. Error handling middleware
As the name implies, it refers to what we do when we can't match the route. Error handling middleware is basically the same as other middleware, except that it requires developers to provide four arguments.
App.use ((err, req, res, next) = > {res.sendStatus (err.httpStatusCode) .json (err);})
In general, we put error handling at the bottom so that we can deal with errors centrally.
Const express=require ("express"); var app=express (); app.get ("/", function (req,res,next) {const err=new Error ('Not Found'); res.send ("Home Page"); next (err);}); app.use ("/ user", function (err,req,res,next) {console.log ("user login"); next (err);}, function (req,res,next) {res.send ("user login") Next ();}); app.use (function (req,res) {res.status (404). Send ("specified page not found"); app.listen (8080); 4. Built-in middleware
Starting with version 4.x, Express is no longer dependent on Content, which means that Express's previous built-in middleware is a separate module, and express.static is the only built-in middleware for Express.
Express.static (root, [options])
With express.static, we can specify the static resources to load.
5. Third-party middleware
Like our previous body-parser, it uses the introduction of external modules to obtain more application operations. Such as cookie and session in the later stage.
Var express = require ('express'); var app = express (); var cookieParser = require (' cookie-parser'); at this point, the study of "what is the get/post request method in nodejs" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.