http://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001471133885340dad9058705804899b1cc2d0a10e7dc80000
for..of for..in 區(qū)別
簡單說仿野,for in是遍歷鍵名阱扬,for of是遍歷鍵值哨毁。例如:
let arr = ["a","b"];
for (a in arr) {
console.log(a);//1,2
}
for (a of arr) {
console.log(a);//a,b
}
const var let 區(qū)別
const定義的變量不可以修改吃既,而且必須初始化.
var定義的變量可以修改港华,如果不初始化會輸出undefined露筒,不會報錯断部。
let是塊級作用域仿粹,函數(shù)內(nèi)部使用let定義后,對函數(shù)外部無影響崭添。
index.js
var fn_index = async (ctx, next) => {
ctx.response.body = `<h1>Index</h1>
<form action="/signin" method="post">
<p>Name: <input name="name" value="koa"></p>
<p>Password: <input name="password" type="password"></p>
<p><input type="submit" value="Submit"></p>
</form>`;
};
var fn_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>`;
}
};
module.exports = {
'GET /': fn_index,
'POST /signin': fn_signin
};
hello.js
var fn_hello = async (ctx, next) => {
var name = ctx.params.name;
ctx.response.body = `<h1>Hello,${name}!</h1>`;
};
module.exports = {
'GET /hello/:name': fn_hello
}
app.js
'use strict';
const fs = require('fs');
const Koa = require('koa');
const router = require('koa-router')();
const bodyParser=require('koa-bodyparser');
const app = new Koa();
var files = fs.readdirSync(__dirname + '/controllers');
console.log('__dirname/controllers: '+__dirname+'/controllers');
var js_files = files.filter((f) => {
return f.endsWith('.js');
});
for (var f of js_files) {
console.log(`process controller: ${f}...`);
let mapping = require(__dirname + '/controllers/' + f);
for (var url in mapping) {
console.log('url----------'+url);
if (url.startsWith('GET ')) {
var path = url.substring(4);
console.log('path--------'+path);
console.log('mapping[url]--------'+mapping[url]);
router.get(path, mapping[url]);
console.log(`register URL mapping: GET ${path}`);
} else if (url.startsWith('POST')) {
var path = url.substring(5);
router.post(path, mapping[url]);
console.log(`register URL mapping: POST ${path}`);
} else {
console.log(`invalid URL :${url}`);
}
}
}
app.use(bodyParser());
app.use(router.routes());
app.listen(3000);
console.log(`app started at port 3000`);
package.json
{
"name": "hello-koa2",
"version": "1.0.0",
"description": "Hello Koa 2 example with async",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"keywords": [
"koa",
"async"
],
"author": "Michael Liao",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/michaelliao/learn-javascript.git"
},
"dependencies": {
"koa": "2.0.0",
"koa-router": "7.0.0",
"koa-bodyparser": "3.2.0"
}
}
記得npm install