【node學習】koa2搭建簡單的伺服器,讀取json檔案開啟圖表專案
阿新 • • 發佈:2018-12-26
需求:用koa2搭建一個簡單的伺服器,能夠讀取json檔案開啟echarts圖表專案。我們知道,不能直接開啟圖表檔案,可以使用hbuilder這種自帶內建伺服器的編輯器,或者vscode的live-server外掛開啟。如果不想在電腦上下載很多編輯器,可以手動用node搭建一個。
1.安裝koa2
# 初始化package.json
npm init
# 安裝koa2
npm install koa
2.我的目錄結構是這樣的,可以根據自己的喜好設定
3.開啟服務
let Koa = require('koa') let app = new Koa() app.listen(3003) console.log('server running at http://localtion:3003')
4.html頁面需要引入靜態css、js等檔案,所以需要node開啟靜態資源請求服務,這裡我使用的koa-static中介軟體
npm install --save koa-static //安裝koa-static外掛
const static = require('koa-static') //靜態資源服務外掛 const staticPath = './src/static' //根基自己的目錄配置檔案路徑 // 配置靜態web服務的中介軟體 app.use(static( path.join( __dirname, staticPath) ))
4.配置專案路由,這裡只是讀取html,展示頁面
npm install koa-router //安裝koa-router外掛
var Router = require('koa-router'); var router = new Router(); const fs = require('fs') //檔案操作 router.get('/',async (ctx)=>{ ctx.response.type = 'html' ctx.response.body = fs.createReadStream('./src/pie.html') //替換自己需要的路徑 }) router.get('/line',async (ctx)=>{ ctx.response.type = 'html' ctx.response.body = fs.createReadStream('./src/line.html') }) router.get('/bar',async (ctx)=>{ ctx.response.type = 'html' ctx.response.body = fs.createReadStream('./src/bar.html') }) ... /*啟動路由*/ app.use(router.routes()) .use(router.allowedMethods());
到此為止,一個最簡單的koa靜態伺服器就搭建好了。
開啟服務命令:node app.js。也可以在package.json裡配置一下。npm start開啟服務
我的app.js檔案(有需要的時候自己再來複制,哈哈)
let Koa = require('koa')
let app = new Koa()
const fs = require('fs')
const static = require('koa-static') //靜態資源服務外掛
var Router = require('koa-router');
var router = new Router();
const path = require('path')
const staticPath = './src/static'
// 配置靜態web服務的中介軟體
app.use(static(
path.join( __dirname, staticPath)
))
router.get('/',async (ctx)=>{
ctx.response.type = 'html'
ctx.response.body = fs.createReadStream('./src/pie.html')
})
router.get('/line',async (ctx)=>{
ctx.response.type = 'html'
ctx.response.body = fs.createReadStream('./src/line.html')
})
router.get('/bar',async (ctx)=>{
ctx.response.type = 'html'
ctx.response.body = fs.createReadStream('./src/bar.html')
})
router.get('/map',async (ctx)=>{
ctx.response.type = 'html'
ctx.response.body = fs.createReadStream('./src/map.html')
})
router.get('/mapv',async (ctx)=>{
ctx.response.type = 'html'
ctx.response.body = fs.createReadStream('./src/map-server.html')
})
router.get('/nav',async (ctx)=>{
ctx.response.type = 'html'
ctx.response.body = fs.createReadStream('./src/nav.html')
})
/*啟動路由*/
app.use(router.routes())
.use(router.allowedMethods());
app.listen(3003)
console.log('server running at http://localtion:3003')