express與koa對(duì)比

這里有比較給力的,大神寫(xiě)的很清楚:https://eggjs.org/zh-cn/intro/egg-and-koa.html

一、起步比較

原生node

var http = require('http');

http.createServer(function (request, response) {

    // 發(fā)送 HTTP 頭部 
    // HTTP 狀態(tài)值: 200 : OK
    // 內(nèi)容類(lèi)型: text/plain
    response.writeHead(200, {'Content-Type': 'text/plain'});

    // 發(fā)送響應(yīng)數(shù)據(jù) "Hello World"
    response.end('Hello World\n');
}).listen(8888);

// 終端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');

express

//express_demo.js 文件
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("應(yīng)用實(shí)例,訪(fǎng)問(wèn)地址為 http://%s:%s", host, port)
 
})

koa

// 導(dǎo)入koa,和koa 1.x不同,在koa2中,我們導(dǎo)入的是一個(gè)class,因此用大寫(xiě)的Koa表示:
const Koa = require('koa');

// 創(chuàng)建一個(gè)Koa對(duì)象表示web app本身:
const app = new Koa();

// 對(duì)于任何請(qǐng)求,app將調(diào)用該異步函數(shù)處理請(qǐng)求:
app.use(async (ctx, next) => {
    await next();
    ctx.response.type = 'text/html';
    ctx.response.body = '<h1>Hello, koa2!</h1>';
});

// 在端口3000監(jiān)聽(tīng):
app.listen(3000);
console.log('app started at port 3000...');

二、請(qǐng)求和響應(yīng)

express

app.get('/', function (req, res) {
   // request 和 response 對(duì)象來(lái)處理請(qǐng)求和響應(yīng)的數(shù)據(jù)
})

koa

參數(shù)ctx是由koa傳入的封裝了request和response的變量,我們可以通過(guò)它訪(fǎng)問(wèn)request和response,next是koa傳入的將要處理的下一個(gè)異步函數(shù)。

async (ctx, next) => {
    await next();
    // 設(shè)置response的Content-Type:
    ctx.response.type = 'text/html';
    // 設(shè)置response的內(nèi)容:
    ctx.response.body = '<h1>Hello, koa2!</h1>';
}

三、路由

原生node

var server = require("./server");
var router = require("./router");
 
server.start(router.route);

express

//  GET 請(qǐng)求
app.get('/', function (req, res) {
   console.log("主頁(yè) GET 請(qǐng)求");
   res.send('Hello GET');
}) 
//  POST 請(qǐng)求
app.post('/', function (req, res) {
   console.log("主頁(yè) POST 請(qǐng)求");
   res.send('Hello POST');
})

koa

//  GET 請(qǐng)求    寫(xiě)法1:
app.use(async (ctx, next) => {
    if (ctx.request.path === '/') {
        ctx.response.body = 'index page';
    } else {
        await next();
    }
});
//  GET 請(qǐng)求    寫(xiě)法2:
const Koa = require('koa');
const router = require('koa-router')();// 注意require('koa-router')返回的是函數(shù):
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...');



四、靜態(tài)文件

express

//  Express 提供了內(nèi)置的中間件 express.static 來(lái)設(shè)置靜態(tài)文件如:img, CSS, JavaScript 等。
app.use('/public', express.static('public'));

koa

// 方法一:自己寫(xiě)一個(gè)處理方法
let staticFiles = require('./static-files');
app.use(staticFiles('/static/', __dirname + '/static'));

// 方法二:引一個(gè)包
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());

/**靜態(tài)資源(服務(wù)端) */
app.use(serve(path.join(__dirname + "/public")));

// 初始化ejs,設(shè)置后綴為html,文件目錄為`views`
render(app, {
    root: path.join(__dirname, 'views'),
    layout: false,
    viewExt: 'html',
    cache: false,
    debug: false
});
// 監(jiān)聽(tīng)3000端口
app.listen(3000);

五、get\post傳參接收方法

原生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'});
 
    // 解析 url 參數(shù)
    var params = url.parse(req.url, true).query;
    res.write("網(wǎng)站名:" + params.name);
    res.write("\n");
    res.write("網(wǎng)站 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 () {
    // 解析參數(shù)
    body = querystring.parse(body);
    // 設(shè)置響應(yīng)頭部信息及編碼
    res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});
 
    if(body.name && body.url) { // 輸出提交的數(shù)據(jù)
        res.write("網(wǎng)站名:" + body.name);
        res.write("<br>");
        res.write("網(wǎng)站 URL:" + body.url);
    } else {  // 輸出表單
        res.write(postHTML);
    }
    res.end();
  });
}).listen(3000);

express

get 傳參接收方法

app.get('/process_get', function (req, res) {
 
   // 輸出 JSON 格式
   var response = {
       "first_name":req.query.first_name,
       "last_name":req.query.last_name
   };
   console.log(response);
   res.end(JSON.stringify(response));
})

post傳參接收方法

app.post('/process_post', urlencodedParser, function (req, res) {
 
   // 輸出 JSON 格式
   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());

六、cookie管理

express

使用中間件向 Node.js 服務(wù)器發(fā)送 cookie 信息

// express_cookie.js 文件
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)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容