当前位置:网站首页>Nodejs framework express and KOA
Nodejs framework express and KOA
2022-06-26 12:26:00 【C+ Ankou wood】
The framework is introduced
express The framework is based on Node.js Minimalism of the platform 、 agile web Application development framework , Based mainly on Connect middleware , And it encapsulates the route itself 、 View processing and other functions .
koa yes Express The original team is based on ES6 A framework for redevelopment of new features , Based mainly on co middleware , The framework itself does not contain any middleware , Many functions need to be solved with the help of third-party middleware , But because it's based on ES6 generator Asynchronous process control of features , It's solved “callback hell” And troublesome error handling problems .
The same thing
Both frames are correct http It was packaged . dependent api Almost. , Written by the same group .
Difference
express There are many built-in middleware available , and koa No, .
express Include routing , View rendering and other features , and koa Only http modular .
express The middleware model of is linear , and koa The middleware model is U type , It can also be called onion model construction middleware .
express Implement asynchronous functions through callbacks , In multiple callbacks 、 It is easy to write logic confusion in multiple middleware .
One 、 start : Create a simple server
Native node
var http = require('http');
http.createServer(function (request, response) {
// send out HTTP Head
// HTTP The status value : 200 : OK
// Content type : text/plain
response.writeHead(200, {
'Content-Type': 'text/plain'});
// Send response data "Hello World"
response.end('Hello World\n');
}).listen(8888);
// The terminal prints the following information
console.log('Server running at http://127.0.0.1:8888/');
// or
const app=http.createServer()
app.on('request',(req,res)=>{
})
express
//express_demo.js file
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log(" Application example , The visiting address is http://%s:%s", host, port)
})
koa
// Import koa, and koa 1.x Different , stay koa2 in , What we import is a class, So in capital Koa Express :
const Koa = require('koa');
// Create a Koa Objects represent web app In itself :
const app = new Koa();
// For any request ,app This asynchronous function will be called to process the request :
app.use(async (ctx, next) => {
await next();
ctx.response.type = 'text/html';
ctx.response.body = '<h1>Hello, koa2!</h1>';
});
// In the port 3000 monitor :
app.listen(3000);
console.log('app started at port 3000...');
Two 、 Requests and responses
express
app.get('/', function (req, res) {
// request and response Object to process request and response data
})
koa
Parameters ctx By koa The incoming package request and response The variable of , We can visit through it request and response,next yes koa The next asynchronous function passed in to be processed .
async (ctx, next) => {
await next();
// Set up response Of Content-Type:
ctx.response.type = 'text/html';
// Set up response The content of :
ctx.response.body = '<h1>Hello, koa2!</h1>';
}
3、 ... and 、 route
Native node
var server = require("./server");
var router = require("./router");
server.use(router.route);
express
// GET request
app.get('/', function (req, res) {
console.log(" Home page GET request ");
res.send('Hello GET');
})
// POST request
app.post('/', function (req, res) {
console.log(" Home page POST request ");
res.send('Hello POST');
})
koa
// GET request How to write it 1:
app.use(async (ctx, next) => {
if (ctx.request.path === '/') {
ctx.response.body = 'index page';
} else {
await next();
}
});
// GET request How to write it 2:
const Koa = require('koa');
const router = require('koa-router')();// Be careful require('koa-router') It returns a function :
const app = new Koa();
// add url-route:
router.get('/hello/:name', async (ctx, next) => {
var name = ctx.params.name;
ctx.response.body = `<h1>Hello, ${
name}!</h1>`;
});
router.get('/', async (ctx, next) => {
ctx.response.body = '<h1>Index</h1>';
});
// add router middleware:
app.use(router.routes());
app.listen(3000);
console.log('app started at port 3000...');
Four 、 Static files
express
// Express Provides built-in middleware express.static To set static files such as :img, CSS, JavaScript etc. .
app.use('/public', express.static('public'));
koa
// Method 1 : Write a processing method by yourself
let staticFiles = require('./static-files');
app.use(staticFiles('/static/', __dirname + '/static'));
// Method 2 : Introduce a package
const Koa = require('koa');
const app = new Koa();
const bodyParser = require('koa-bodyparser');
const Router = require('koa-router');
const router = new Router();
const render = require('koa-ejs');
const path = require('path');
const serve = require('koa-static');
app.use(bodyParser());
/** Static resources ( Server side ) */
app.use(serve(path.join(__dirname + "/public")));
// initialization ejs, Set the suffix to html, The file directory is `views`
render(app, {
root: path.join(__dirname, 'views'),
layout: false,
viewExt: 'html',
cache: false,
debug: false
});
// monitor 3000 port
app.listen(3000);
5、 ... and 、get\post Method of transmitting and receiving parameters
Native node
// get
var http = require('http');
var url = require('url');
var util = require('util');
http.createServer(function(req, res){
res.writeHead(200, {
'Content-Type': 'text/plain'});
// analysis url Parameters
var params = url.parse(req.url, true).query;
res.write(" The websites :" + params.name);
res.write("\n");
res.write(" Website URL:" + params.url);
res.end();
}).listen(3000);
// post
var http = require('http');
var querystring = require('querystring');
http.createServer(function (req, res) {
var body = "";
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
// Analytical parameters
body = querystring.parse(body);
// Set response header information and code
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf8'});
if(body.name && body.url) {
// Output submitted data
res.write(" The websites :" + body.name);
res.write("<br>");
res.write(" Website URL:" + body.url);
} else {
// Output form
res.write(postHTML);
}
res.end();
});
}).listen(3000);
express
get Method of transmitting and receiving parameters
app.get('/process_get', function (req, res) {
// Output JSON Format
var response = {
"first_name":req.query.first_name,
"last_name":req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
post Method of transmitting and receiving parameters
app.post('/process_post', urlencodedParser, function (req, res) {
// Output JSON Format
var response = {
"first_name":req.body.first_name,
"last_name":req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
koa
// POST
const bodyParser = require('koa-bodyparser');
router.post('/signin', async (ctx, next) => {
var
name = ctx.request.body.name || '',
password = ctx.request.body.password || '';
console.log(`signin with name: ${
name}, password: ${
password}`);
if (name === 'koa' && password === '12345') {
ctx.response.body = `<h1>Welcome, ${
name}!</h1>`;
} else {
ctx.response.body = `<h1>Login failed!</h1> <p><a href="/">Try again</a></p>`;
}
});
app.use(bodyParser());
6、 ... and 、cookie management
express
Use middleware to Node.js Server send cookie Information
// express_cookie.js file
var express = require('express')
var cookieParser = require('cookie-parser')
var util = require('util');
var app = express()
app.use(cookieParser())
app.get('/', function(req, res) {
console.log("Cookies: " + util.inspect(req.cookies));
})
app.listen(8081)
Here are some awesome , Written by the great God Egg.js And Koa:https://eggjs.org/zh-cn/intro/egg-and-koa.html
边栏推荐
- 我想知道同花顺是炒股的么?在线开户安全么?
- Vulnerability scanning and reverse osmosis of Internet anti artifact
- Five strategies and suggestions of member marketing in consumer goods industry
- 开通证券账户需要注意事项 开户安全吗
- Scala-day01- companion objects and HelloWorld
- Cross platform members get through the two channels of brand Ren Du
- Comparison of latest mobile phone processors in 2020 (with mobile phone CPU ladder diagram)
- File decryption in webgame development
- Vscode solves the problem of Chinese garbled code
- Php+laravel5.7 use Alibaba oss+ Alibaba media to process and upload image / video files
猜你喜欢

leetcode 715. Range 模块 (hard)

This executeQuery (SQL) cannot compile classes for JSP. What is the reason?

Deep thinking from senior member managers

Mysql8 master-slave replication
![[solved] data duplication or data loss after laravel paginate() paging](/img/68/7bf51bbf893a91bee24f5f7d4a369f.jpg)
[solved] data duplication or data loss after laravel paginate() paging

Scala-day02- variables and data types

Introduction to the four major FPGA manufacturers abroad

New routing file in laravel framework

Examples of how laravel uses with preload (eager to load) and nested query

Php+laravel5.7 use Alibaba oss+ Alibaba media to process and upload image / video files
随机推荐
Precautions for opening a securities account is it safe to open an account
[solved] laravel completes the scheduled job task (delayed distribution task) [execute a user-defined task at a specified time]
Measures to support the development of cultural and creative industries in Futian District, Shenzhen
Matlab programming example: how to count the number of elements in a cell array
Leetcode 78. 子集 and 90. 子集 II
UDP protocol details [easy to understand]
What determines the rent
Several problems encountered in setting up the environment in the past two days
Cross platform members get through the two channels of brand Ren Du
Common problems and Thoughts on member operation management
One click deployment CEPH script
4. N queen problem
Refined operation, extending the full life cycle value LTV
这两天搭建环境遇到的几个问题
CG骨骼动画
Assembly language (7) operation instruction
PHP laravel+gatewayworker completes im instant messaging and file transfer (Chapter 1: basic configuration)
Vscode solves the problem of Chinese garbled code
国际美妆业巨头押注中国
This executeQuery (SQL) cannot compile classes for JSP. What is the reason?