nodejs框架koa常用配置
文章目錄
- nodejs基礎
- express
- koa
- hello world
- koa路由
- nodemon 監(jiān)控文件修改
- koa中間件
- 設置靜態(tài)目錄
- 獲取請求參數(shù)
- 使用模板
- 跨域配置
- 使用vscode調(diào)試接口(下班回家了,明天再寫)
nodejs基礎(參考菜鳥教程的nodejs教程 )
- JavaScript語法
- 創(chuàng)建服務器模塊http
- 文件讀取模塊fs
- 路徑path
- 模塊系統(tǒng) require寡润、module.exports
- es6語法(新版本的nodejs除了模塊外全部支持
nodejs框架-express
文檔地址:http://www.expressjs.com.cn/
nodejs框架-koa
中文文檔地址:https://koa.bootcss.com/
node模塊倉庫地址:https://www.npmjs.com/
koa之hello world
-
初始化package.json
新建目錄koademo,執(zhí)行 npm init瓷式,一路回車
-
創(chuàng)建一個簡單的koa應用(hello world)
安裝koa模塊 npm install koa --save
在項目根目錄新建app.js殖妇,app.js代碼如下:
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
3. 執(zhí)行node app.js
4. 用瀏覽器訪問 http://localhost:3000
koa路由(一) koa-simple-router
https://www.npmjs.com/package/koa-simple-router
安裝 koa-simple-router模塊点骑,然后修改上面的app.js代碼刨肃,變成下面這個樣子
const Koa = require('koa')
const router = require('koa-simple-router')
const app = new Koa()
app.use(router(_ => {
_.get('/', (ctx, next) => {
ctx.body = 'hello world';
})
_.post('/path', (ctx, next) => {
})
// 同時支持get和post請求
_.all('/login', (ctx, next) => {
ctx.body = {
code: 666,
msg: '登錄成功'
}
})
_.all('/regester', (ctx, next) => {
ctx.body = {
code: 666,
msg: '注冊成功'
}
})
}))
app.listen(3000,()=>{
console.log('服務已啟動圃阳,在 http://localhost:3000/');
});
啟動服務孽文,用瀏覽器訪問
http://localhost:3000/login 和
http://localhost:3000/register
為了讓代碼結構性更好,我們可以把路由這部分單獨放在一個文件里
kao路由(二) koa-router(我目前用這個)
創(chuàng)建新文件夾koa-app作為項目的跟目錄
-
使用終端(命令提示符或者powershell)進入根目錄,初始化package.json
npm init -y
-
安裝koa和koa-router
npm i koa koa-router --save-dev
-
新建app.js,代碼如下
const Koa = require('koa') const Router = require('koa-router') const app = new Koa() const router = new Router(); router.get('/', ctx => { ctx.body = 'hello world' }) router.get('/demo1', ctx => { ctx.body = 'demo1' }) router.post('/demo1', ctx => { ctx.body = 'demo1' }) router.all('/demo2', ctx => { ctx.body = 'demo2' }) app.use(router.routes()); app.listen(3000, () => { console.log('服務已啟動夺艰,在 http://localhost:3000/'); });
啟動服務芋哭,用瀏覽器訪接口即可
-
封裝router,我們一般會把router單獨放到一個文件,然后倒入到app.js使用
const Router = require('koa-router') const router = new Router(); router.all('/', ctx => { ctx.body = 'hello world' }) router.all('/add', ctx => { ctx.body = 'add' }) router.all('/getList', ctx => { ctx.body = 'demo1' }) router.all('/del', ctx => { ctx.body = 'del' }) router.all('/edit', ctx => { ctx.body = 'edit' }) module.exports = router;
app.js里的代碼變成這樣
const Koa = require('koa') const app = new Koa() const router = require('./router'); app.use(router.routes()); app.listen(3000, () => { console.log('服務已啟動,在 http://localhost:3000/'); });
服務器自動重新部署
我們發(fā)現(xiàn)沒修改一次代碼郁副,都必須重啟才能生效减牺,這顯然不方便,我們希望修改了文件服務能自動重啟.能實現(xiàn)這樣功能的node模塊有下面兩個.
- nodemon和supervisor
- 全局安裝npm i nodemon -g 或 npm i supervisor -g
- 啟動服務的時候用nodemon app.js 或 supervisor app.js代替node app.js
koa中間件
一個請求從發(fā)出到返回數(shù)據(jù),如果我們想在這個過程里做一些統(tǒng)一的操作,可以使用中間件來完成.
中間件是個函數(shù)
-
使用中間件的方式, app.use(中間件)
app.use((ctx, next) => { // 在ctx上放入username,后面的所有請求的ctx里都會有username這個變量 ctx.username = '我是老胡'; // 處理完之后放行,不使用next()的話,程序會被掛起來不動了 next(); // 在vue路由守衛(wèi)里曾使用過next })
中間件有順序
設置靜態(tài)目錄
在目錄中創(chuàng)建目錄static霞势,在public下創(chuàng)建文件demo.html烹植,訪問http://localhost:3000/public/demo.html是無法訪問得到,因為我們還沒有設置靜態(tài)資源目錄,設置靜態(tài)資源目錄要用到koa-static模塊
-
安裝koa-static
npm i koa-static --save-dev
在app.j是里加入如下代碼
const serv = require('koa-static');
app.use(serv(__dirname + '/static'));
再來訪問 http://localhost:3000/demo.html 就可以訪問了,ps: 路徑不用加public
獲取請求參數(shù)
給剛才的demo.html添加axios用來發(fā)送請求愕贡,代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js"></script>
</head>
<body>
<h3>
測試koa靜態(tài)資源目錄
</h3>
<script>
let url = 'http://localhost:3000/add';
let data = {
params: {
username: 'laohu',
phone: 13800000000
}
}
axios.get(url, data).then(res => {
console.log(res);
})
</script>
</body>
</html>
- 獲取get請求參數(shù)
在router.js的add接口里加入如下代碼
router.all('/add', ctx => {
// 獲取get請求參數(shù)
const username = ctx.query.username;
const phone = ctx.query.phone;
// 把拿到的數(shù)據(jù)放入ctx.body
ctx.body = {
module: 'add',
username,
phone
}
})
-
獲取post請求
獲取post請求需要使用koa-body模塊
安裝koa-body npm i koa-body --savenpm i koa-body --save
在app.js里加入如下代碼:
const koaBody = require('koa-body');
app.use(koaBody());
獲取post請求參數(shù)的代碼如下
ctx.request.body.xxx
使用模板
一般請求一個接口返回的是一坨數(shù)據(jù),然而有時候我們希望返回的是一個html網(wǎng)頁或者一段html代碼(上周分享的服務器渲染)
我們試用koa-swig模塊來向前端返回一個html
- 安裝koa-swig
npm i koa-swig --save-dev
在根目錄創(chuàng)建views目錄巷屿,在views目錄下創(chuàng)建tpl.html,代碼如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h3><%=title %></h3>
<ul>
<%
list.forEach(item=>{
%>
<li><%=item.username %> => <%=item.age %></li>
<%
})
%>
</ul>
</body>
</html>
- 在app.js添加如下代碼:
const views = require("koa-views");
app.use(views(path.join(__dirname, "views"), {
map: {
html: 'underscore'
}
}));
// 在路由中使用
router.all('/', async ctx => {
const list = [{
username: '約書亞',
age: 22
},
{
username: '亞伯拉罕',
age: 100
},
{
username: '挪亞',
age: 500
}
]
await ctx.render('tpl', {
title: 'kao-框架實戰(zhàn)',
list
});
})
- 訪問 http://localhost:3000固以,就可以看到一個html頁面
ps: 要訪問一個接口,吐出一個頁面你還可以直接在js里使用反引號``拼接模板,當然也可以使用vue來渲染
跨域配置
自己編寫一個中間件即可,代碼如下
// 跨域設置
app.use(async (ctx, next) => {
ctx.set("Access-Control-Allow-Origin", "*");
await next();
})
訪問剛才的demo.html文件, http://localhost:3000/demo.html,你會發(fā)現(xiàn)你的請求的響應頭上添加了Access-Control-Allow-Origin: *,說明服務器跨域設置已經(jīng)成功了.
demo地址
(未完待續(xù))
相關文章:
mongoose常用操作
egg+mongodb 配置
koa+mogodb創(chuàng)建簡單的增刪改查項目(待更新)