【node学习】koa2搭建简单的服务器,读取json文件打开图表项目

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33168578/article/details/83180262

需求:用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')

猜你喜欢

转载自blog.csdn.net/qq_33168578/article/details/83180262
今日推荐