Node.js Express framework learning

1. Introduction to Express

Express is a simple and flexible node.js web application framework, providing a series of powerful features to help create various web applications, and a wealth of HTTP tools.

Use Express to quickly build a fully functional website.

1.Express framework core features:
  • You can set up middleware to respond to HTTP requests.
  • The routing table is defined to perform different HTTP request actions.
  • You can dynamically render HTML pages by passing parameters to the template.
2. Description of Express framework files:

Insert picture description here
(1) bin--> Startup configuration file
(2) node_modules--> Store all project dependent libraries
(3) public--> Static files, css, js, img...
(4) routes--> Routing file
(5) views--> Page File, the default engine is .jade
(6) app.js--> Application core configuration file

Two, routing routes

Access to the database, interface implementation

app.method(path,function(req,res,next){ 函数代码 })
Parameter description:
app: express instance
method: request method get/post
function: the function to be executed when the route is matched, there are multiple route handlers, if it is not the last route, the function needs the third parameter next

(1) Create routing file:
Insert picture description here(2) Configure routing file in app.js file

Insert picture description here

1.get request

Features: Can be cached, saved as bookmarks, kept in the browser history, has a length limit, should not be used when processing sensitive data, and should only be used to retrieve data

Get the front desk get request:req.query.参数名

var express = require('express');
var router = express.Router();

// 获取login页面
router.get('/',function(req,res,next){
    
    
  res.render('login')
})

router.get('/login',function(req,res){
    
    
  // 获取前台get请求
  console.log(req.query)
  res.send('登录路由,user为:'+req.query.username+'==>   paddword为:'+req.query.userpwd)
})

module.exports = router;

Front desk code:

<form action="http://localhost:9897/login" method="GET">
    用户名:<input type="text" name="username">
    <br>
    密  码:<input type="password" name="userpwd">
    <br>
    <input type="submit" value="确认">
</form>
2.post request

Get the post request:req.body.参数名

var express = require('express');
var router = express.Router();

// 测试post请求
router.post('/add',function(req,res){
    
    
  console.log(req.query)
  res.send('post请求:用户名:'+req.body.adminname+'<br>密码:'+req.body.adminpwd)
})
module.exports = router;

Front desk code:

<form action="http://localhost:9897/add" method="post">
    用户名:<input type="text" name="adminname">
    <br>
    密  码:<input type="password" name="adminpwd">
    <br>
    <input type="submit" value="确认">
</form>

Three, request and response

Express application callback function parameters: requestand responseobject to handle the request and response data.

app.get('/', function (req, res) {
    
    

})
1.Request object
  • The request object represents an HTTP request, including attributes such as the request query string, parameters, content, and HTTP headers.
  • Common attributes are:
Attributes Description
req.app When the callback is an external file, use req.app to access the express instance
req.baseUrl Get the URL path of the route currently installed
req.body / req.cookies Get "Request Subject" / Cookies
req.fresh / req.stale Determine whether the request is still "fresh"
req.hostname / req.ip Get hostname and IP address
req.originalUrl Get the original request URL
req.params Get routing parameters
req.path Get request path
req.protocol Get agreement type
req.query Get the query parameter string of the URL
req.route Get the currently matched route
req.subdomains Get subdomain
req.accepts() Check acceptable requested document types
req.acceptsCharsets / req.acceptsEncodings / req.acceptsLanguages Returns the first acceptable character encoding of the specified character set
req.get() Get the specified HTTP request header
req.is() Determine the MIME type of the Content-Type of the request header
2.Response object
  • The response object represents the HTTP response, that is, the HTTP response data sent to the client when the request is received.
  • Common attributes are:
Attributes Description
res.app Same as req.app
res.append() Append the specified HTTP header
res.set() After res.append(), the previously set header will be reset
res.cookie(name,value [,option]) 设置Cookie ;opition: domain / expires / httpOnly / maxAge / path / secure / signed
res.clearCookie() Clear cookies
res.download() Transfer files in the specified path
res.get() Return the specified HTTP header
res.json() Send JSON response
res.jsonp () Send JSONP response
res.location() Only set the Location HTTP header of the response, without setting the status code or close response
res.redirect() Set the Location HTTP header of the response, and set the status code 302
res.render(view,[locals],callback) Render a view and pass the rendered string to the callback. If an error occurs during the rendering process, next(err) will be called automatically. The callback will be passed in a possible error and the rendered page so that it will not be output automatically.
res.send() Send HTTP response
res.sendFile(path [,options] [,fn]) Send the file of the specified path-the Content-Type will be automatically set according to the file extension
res.set() Set HTTP headers, you can set multiple headers at once when you pass in object
res.status() Set HTTP status code
res.type() Set the MIME type of Content-Type
  • The difference between res.redirect() and res.render(): (both can achieve page jump)
    res.redirect() -->Request forwarding: Jump on the server side, and only generate a request object
    res.render()- ->Page redirection: When redirecting on the client side, two request objects will be generated

Guess you like

Origin blog.csdn.net/isfor_you/article/details/114372097