express

npm init 
npm install ejs body-parser express
Copy the code

http.server

let http = require('http');
const url = require('url');
http.createServer(function (req, res) {
  let { query, pathname } = url.parse(req.url, true);
  if (pathname == '/signin') {
    let str = ' ';
    req.on('data'.function (chunk) {
      str += chunk;
    })
    req.on('end'.function () {
      console.log(str);
    })
    res.setHeader('Content-Type'.'text/plain; charset=utf8');
    return res.end('login')}if (pathname == '/signup') {
    res.setHeader('Content-Type'.'text/plain; charset=utf8');
    return res.end('registered')
  }

}).listen(8080);
Copy the code
const express = require('express'); Const app = express(); const app = express(); // The express function returns an HTTP listener, which is the same function in http.createServer. // The test function extends listen to listen on port app.listen =function(... args){ require('http').createServer(app).listen(... args); } // app.listen is based on the previous package // app.listen(8080,function(){
//   console.log(`start8080`)
// })
Copy the code

express route

const express = require('express');
const app = express();
app.listen(3000, ()=>{
  console.log('Run at 3000')}); // App listener extends many methods, including get, POST, delete, put, RESful style verbs // app. The method name ('Pathname'// The path knows the pathname and does not say hello to the following content // Express focus on extending req and res properties app.get('/signin'.function(req, res){
  res.setHeader('Content-Type'.'text/plain; charset=utf8');
  res.end('login')}); app.post('/signup'.function(req, res){
  res.end('registered')}); app.all(The '*'.function(req, res){
  res.end('404');
})
Copy the code

req.attribute

const express = require('express'); const app = express(); app.listen(8080); // select one or all app.get('/user'.function(req, res) { console.log(req.query.id); console.log(req.url); console.log(req.path); console.log(req.headers); // All lowercase console.log(req.method); // all caps})Copy the code

route params

const express = require('express'); const app = express(); app.listen(8080); // /user? /user/1 = /user/1 = /user/ 2 = /user/1 = /user'/user'.function (req, res) {
  res.end('select all')}); // user/1/2=>{id:1, name:2} = params; One-to-one correspondence app.get('/user/:id/:name'.function (req, res) {
  res.end('select one'+req.params.id+req.params.name);
});

let url = '/user/1/2/a';
let url2 = '/user/:id/:name/a'; // {id:1, name:2} // Convert url2 into a url matching relet arr = [];
let newReg = url2.replace(/:[^\/]+/g, function(){
  arr.push(arguments[0].slice(1));
  return '(/ [^ \] +)'
});
let reg = new RegExp(newReg);
let newArr = reg.exec(url);
let result = {};
arr.forEach(function(item, index){
  result[item] = newArr[index+1]
});
console.log(result);
const express = require('express'); const app = express(); app.listen(8080); // Req and res are the same app.param('id'.function(req, res, next){
    letReq.params. id = 'Your student id is${req.params.id}`;
    next();
});
app.param('name'.function(req, res, next){
    letReq.params. name = 'Your name is${req.params.name}`;
    next();
});
app.get('/user/:id/:name'.function (req, res) {
    res.header('Content-typy'.'text/plain; charset=utf-8')
    res.end(`${req.params.id}${req.params.name}`);
});

Copy the code

7. MiddleWare

What is executed before we access the final goal

const express = require('express'); const app = express(); app.listen(8080); //2. Req and RES can be extended //3. Middleware is placed above the execution path //4. Middleware matches by default.'/water'.function(req, res, next){// Do not call next do not continue down console.log('Filter stone');
    req.stone = 'too big';
    next('wrong'); });});}); app.use('/water'.function(req, res, next){// Do not call next do not continue down console.log('Filter sand');
    req.send = 'too small'; next(); }); // app.use(function(req, res, next){
    res.header('Content-type'.'text/plain; charset=utf-8');
    next();
})
app.get('/water/a'.functionConsole. log(req. Stone, req. Send) res.end(req.'water');
})
app.get('/food'.function(req, res){
    console.log(req.stone, req.send)
    res.end('food');
})
app.use(function(err, req, res, next){// Error middleware has four arguments fn.length === 4 console.log(err); })Copy the code

example

const express = require('express');
const app = express();
app.listen(8080);

app.use(function(req, res, next){
    lett = new Date().getTime(); // Access the original time, and record the end timelet end = res.end;
    res.end = function(... arg){ end.call(res,... arg); } next(); }); app.get('water'.function(req, res){
    for(leti=0; i<1000, i++){ } res.end('water'); // Decorate mode}); app.get('food'.function(req, res){
     for(leti=0; i<10000, i++){ } res.end('food');
})
Copy the code

decorator

function coffee(){
    console.log('Have a cup of coffee');
}
function sweetCoffee(){
    coffee();
    console.log('sugar') } coffee(); sweetCoffee(); Next principle middleWare implementationfunction app(){} // Every time the use method is called, the method is stored in the array. By default, the first item in the array is called, and the next method is passed to the array function. app.use =function (cb) {
    this.middleware.push(cb);
}
app.use(function(req, res, next){
    console.log(1);
    next();
});
app.use(function(req, res, next){
    console.log(2);
    next();
});
app.use(function(req, res, next){
    console.log(3);
    next();
});
let index = 0;
function next() {
    app.middleware[index++](null, null, next);
};
next();
Copy the code

Res New methods and properties

const express = require('express'); const app = express(); app.listen(8080); // The object res.json() cannot be returned directly; // return THML page res.sendfile (); Return file // res.statusCode res.end = res.sendStatus(); // res.end() res.header(); = res.send(); app.get('/json'.function(req, res){
    res.json({name:xxx,age: 9});
})
app.get('/'.function(req, res){// root cannot pass.. // res.sendfile (__dirname +'/index.html''); res.sendFile('./index.html',{root: __dirname}); Res.sendfile (require('path').join(__dirname, '.', 'index.html')); }); app.get('/status', function(req, res){ res.sendStatus(404); }); app.use(function(req, res, next){ res.mySend = function(data){ if(typeof data === 'object'){ res.setHeader('Content-Type', 'application/json; chartset=utf8'); return res.send(JSON.stringify(data)); } if(typeof data === 'string'){ res.setHeader('Content-Type', 'text/plain; chartset=utf8'); return res.send(data); } if(typeof data === 'number'){ res.statusCode = data; res.end(require('_http_server').STATUS_CODES[data]); } } next(); }) app.get('/send', function(req, res){ // res.send({name: 'xxx', age: 9}); // res.end(200); res.mySend(); })Copy the code