Download the express package
Install Express locally into the project
npm install express
npm i express
-
The project directory name should not be Chinese, nor express
-
If installation is not successful:
- Change your Network
- run
npm cache clean -f
Run the download command again
Create a Web server quickly using Express
Reference documentation
Create a new js file in the project root directory, such as app.js, and enter the following code:
Const Express = require(' Express ') // 1. Call express() to get an app similar to http.createserver () const app = express() // 2. App.get ('/', (req, res) => {res.send('hello world')}) // 3. Listen (3000, () => console.log(' APP listening on port 3000! '))Copy the code
Description:
- App.get (‘/’) is equivalent to adding an event listener: when the user asks for “/” in get mode, the callback function behind it will be executed. The req and res in the callback function are the same as the HTTP module we learned earlier.
- Res.send () is a supplementary method provided by the ExPRSS framework to the RES object (the RES in the HTTP module does not have this method) to end the request. Similarly, res.json(), res.sendfile ().
Hosting static resources – Web servers
Use static middleware to host static resources to achieve web server
Reference documentation
Giving users direct access to static resources is the most basic function of a Web server.
http://localhost:3000/1.png
http://localhost:3000/css/style.css
http://localhost:3000/js/index.js
Copy the code
For example, the above URL requests an image, a style file, and a JS code, respectively. The Web server we implement needs to be able to return the contents of these files directly to the client browser.
Limit the prefix
// Restrict access to prefix app.use('/public', express.static('public'))Copy the code
This means that to access content under public, you must add /public to the request URL
Routes and Interfaces
Routing is a group of mappings. It specifies how the server responds when a particular HTTP method (GET, POST, and so on) accesses a URL (or path identifier).
format
const app = express(); // Define route app.METHOD(PATH, HANDLER)Copy the code
Among them:
-
App is an instance of Express. (const app = express ())
-
METHOD is an HTTP request METHOD. All lowercase format. For example, post, GET, and delete.
-
PATH is the request PATH (equivalent to url.parse(req.url).pathname used in the HTTP module)
The browser url Server path http://localhost:8080 / http://localhost:8080/public/a/index.html /public/a/index.html http://localhost:8080/index.html?a=1&b=2 /index.html -
HANDLER is the HANDLER function that needs to be executed when a route is matched. (req,res) =>{}
The sample
const express = require('express'); const app = express(); // Route app.get('/get', function(req, res) {// handle logic res.json({name: 'ABC'}); }); app.listen('8088', () => { console.log('8088'); });Copy the code
Note:
- Res.json () is the method provided by Express.
graphic
Write interface – GET Indicates that the interface has parameters
The req. Query attributes
The Express framework automatically collects the query string parameters that get passes from the URL address and stores them in the Query property of the REQ object. We can just get it.
App.get ('/get', function(req, res) {// Return console.log(req.query); });Copy the code
const express = require(‘express’); const app = express(); app.get(‘/get’, function(req, res) { // 直接返回对象 console.log(req.query); res.send({ name: ‘abc’ }); }); app.listen(‘8088’, () => { console.log(‘8088’); });
Write interface – Post interface
Post interface with no parameters
const express = require('express');
const app = express();
app.post('/api/post', function(req, res) {
// 直接返回对象
res.send({ name: 'abc' });
});
app.listen('8088', () => {
console.log('8088');
});
Copy the code
Pass parameters in the request header
const express = require('express'); const app = express(); App. post('/ API /post', function(req, res) {// Return console.log(req.query); res.send({ name: 'abc' }); }); app.listen('8088', () => { console.log('8088'); });Copy the code
A POST interface is different from a GET request
The operations are different: GET is used to query, post is used to add;
Pass parameters are different: GET parameters can only be passed through the query string in the request line, while POST is generally passed through the request body (which can also be passed through the request line).
Parameter format of the request body
According to the format of the parameters passed, it can be divided into three cases
- Pass normal key-value pairs
- Passing json
- Passing the Form (involving file uploads)
Post interface – Normal key-value pair parameters
The target
Express.urlencoded () is used to get the parameters of the request body.
Specifically, when content-Type is X-www-form-urlencoded, ordinary simple key-value pairs uploaded are denoted.
Define the back-end interface
// 1. Use middleware app.use(express.urlencoded()); app.post("/add",function(req,res){ //2. Req.body can be used to retrieve the key value pair res.json(req.body)} passed by post.Copy the code
Note:
- app.use(….) After that, there will be an additional property res.body in res.body.
Postman test
Post interface – The parameter is in JSON format
The target
Use express.json() to get the JSON data passed in the request body.
The back-end
app.use(express.json()); // The req.body attribute is automatically added, App.post ('/postJSON',(req,res)=>{// The backend receives the post pass parameter console.log(req.body); res.send('/postJSON') })Copy the code
When passing parameters through POST, if the parameters to be passed are complex (multi-level nesting), you can upload them in JSON format.
var data = {
name:"abc",
address:{
"a":1,
"b":2,
"info":"c"
}
}
Copy the code
Postman operation
Post Interface -form-data File upload
Multer package
Multer is a Node.js middleware that processes form data of type multipart/form-data. It is mainly used for uploading files.
If file upload operations are involved, the third-party multer package (not express) needs to be used on the server side to obtain uploaded information.
The back-end
1. Install
npm install multer
Copy the code
2. Use
Const multer = require('multer'); Const upload = multer({dest:'uploads/'}) const upload = multer({dest:'uploads/'}) const upload = multer({dest:'uploads/'}) Using // this route uses the second parameter.upload.single to indicate single file uploads and 'cover' to indicate the key name of the file to be uploaded in the last data. Corresponding to on the front page: // <input type="file" name='cover'/> app.post("/postfile", upload.single('cover'), Function (req,res){// req.file // req.body // other common parameters // other operations})Copy the code
Description:
- If uploads is not in the current directory, it automatically creates the uploads folder
upload.single
It just handles file uploads. You can still get other parameters via req.body
Postman test
The operations for Postman are as follows:
Interface parameter transfer concept
Request message: line, header, body
We generally use Ajax technology to request interfaces. According to the convention of HTTP protocol, each request has three parts:
-
Request line: holds the request method, address, and a small amount of data that can be attached in the form of a query string.
-
Request header: It can attach a lot of information, where the Content-Type is used to specify the format of the data to be stored in the request body.
There are three values of content-type:
The value of the content-type Represents the data format of the request body The sample application/x-www-form-urlencode Plain key-value objects a=2&c=1 application/json Json object {a:1,b:{c:1}} multipart/form-data Upload a file file -
Request body: parameter carried in this request. How these parameters should be resolved at the back end is determined by the content-Type in the request header.
The parameter transfer
Method 1: Request line. The common methods are as follows:
- Use Ajax technology to pass parameters through GET.
- Enter the interface address in the browser address bar and add the query string.
Method two: request body.
- Post, PUT, and DELETE in Ajax can pass parameters from the request body.
In addition, the Content-Type in the request header tells the server how to parse the data in the request body.
The back-end processing
Interface rules are dictated by the back end, which specifies the interface: name, parameters, format, and mode.
Interface parameter Transfer – Overall example
The directory structure
-package.json
-node_modules
-public
-------index.html
-server.js
Copy the code
Requirements:
- Localhost: 3000 / index. The HTML can access the index under the public. The HTML file
- The backend implements three interfaces to handle post requests in index. HTML, respectively. Note that the backend only needs to receive the parameters, and does not need to complete the specific functions.
The front end
Use jquery ajax to send requests
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge"> <title>Document</title> </head> <body> <button </button> <hr/> <button ID ="btn_keyvalue"> </button> <hr/> <form ID ="myform"> <input type="text" name="title"> <input type="file" name="cover"> </form> <button Id ="btn_formdata">post- pass formdata</button> <hr/> <script SRC = "https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js" > < / script > < script > / / the most common key/value pair format $('#btn_keyvalue').click(function(){ $.ajax({ type:'post', url:'http://localhost:3000/post', data:{a:1,b:2}, success(res){ console.log(res); } }) }) var obj = { "name":"abc", "address":{ "a":1, "b":2, "Info", "c"}} / / transfer complex JSON object data $(' # btn_json). Click (function () {$. Ajax ({type: "post", url:'http://localhost:3000/postJSON', // contentType: false, contentType: "application/json; charset=UTF-8", data:JSON.stringify(obj), success(res){ console.log(res); $('# btn_formData ').click(function(){var fd = new formData (document.getelementById ('myform')); $.ajax({ type:'post', url:'http://localhost:3000/admin/article_publish', contentType: false, processData:false, data:fd, success(res){ console.log(res); } }) }) </script> </body> </html>Copy the code
The backend interface
Reference code
const express = require('express') const app = express(); App.use (express.static('public')) // Use the package. The req.body attribute is automatically added to subsequent POST requests. This attribute contains the parameters passed to the POST request. Application /x-www-form-urlencoded app.use(express.urlencoded())) // Content-type: application/ JSON; Const multer = require('multer'); app.use(express.json()) const multer = require('multer'); // If this post request involves a file upload, upload it to uploads // content-type: multipart/form-data; var upload = multer({ dest: 'uploads/' }) // formDate app.post('/admin/article_publish',upload.single('cover'),(req,res)=>{ //upload.single('cover') // <input type="file" name="cover" /> // put the file to the specified directory console.log(req.file); // For other parameters, find console.log(req.body) again in req.body; Res. json({code:200, MSG :' uploaded successfully ',info:req.file.path})}) // Common POST key value pair app.post('/post',(req,res)=>{// Expect to receive the POST parameter on the back end console.log(req.body); let obj = req.body obj._t = Date.now(); Res.json (obj)}) // SON format data // content-type: application/json; App.post ('/postJSON',(req,res)=>{// Want the back end to receive post pass parameter console.log(req.body); // res.send('/postJSON') res.json(req.body)}) Get ('/ getAPI ',(req,res)=>{// Get console.log(req.query) from req.query quickly; let obj = req.query obj._t = Date.now(); Res.json (obj)}) app.listen(3000,()=>{console.log(' Express app started on port 3000 '); })Copy the code
RESTful interface
It’s a way of designing interfaces. RESTful design:
- Design resources by URL. Interface names are generally nouns and do not contain verbs.
- The request mode (GET, POST, DELETE, PUT) determines the operation type of the resource
Common Interface Design
- Use only the GET and POST interfaces
- The address of an interface usually consists of a verb and a noun
- The address of each interface is different
Such as:
Interface name: localhost: 8080 / getarticle type: the get function: the article information
Interface name: localhost: 8080 / addarticle types: post function: to add a new article
Interface name: localhost: 8080 / delarticle types: post function: delete articles
Interface name: localhost: 8080 / updatearticle types: post function: edit articles
/ / -- -- -- -- -- -- -- -- -- -- -- -- here is a common API design -- -- -- -- -- -- -- -- -- -- -- -- -- -- - app. Get ('/getarticle '(the req, res) = > {res. Send (' access')}) App. Post ('/addarticle '(the req, res) = > {res. Send (' add')}) app. Post ('/delarticle '(the req, res) = > {res. Send (' delete')}) App. Post ('/updatearticle '(the req, res) = > {res. Send (' editors')})Copy the code