Koa小结

Koa

一、koa是什么?

koa是一个新的WEB框架,致力于成为WEB领域和API开发中的一个更小,更富有表现力的基石。
koa没有任何预置的中间件,可快速的编写服务器端的应用程序。

koa的核心概念

  • Koa Application
  • Context
  • Request、Response
    在这里插入图片描述
npm install -S koa 	//创建koa
node index.js   //启动项目
const Koa = require('koa')
const app = new Koa()

app.use(async ctx => {
	consle.log(ctx.request);
    ctx.body = 'Hello World!'
})

app.listen(3000)//监听端口号

二、koa-router

npm install -S koa-router //-S安装开发生产过程中的依赖,保存在package的dependencies里,打包时dependencies里的应用会打包到最终的js里面去

const Koa = require('koa')
const Router = require('koa-router')

const app = new Koa()
const router = new Router()

router.get('/', ctx => {
    console.log(ctx);
    console.log(ctx.request);
    ctx.body = 'Hello World!'
})

router.get('/api', ctx => {
    console.log(ctx);
    console.log(ctx.request);
    ctx.body = 'Hello API!'
})

app.use(router.routes()) // 把前面定义的所有的路由方法添加到app这个koa应用上去,做一个中间件处理
    .use(router.allowedMethods()) //可想象为拦截器,主要拦截应用中没有的请求,直接返回4XX或5XX

app.listen(3000)

Koa的工作原理
在这里插入图片描述

三、Koa开发RESTful接口

koa-router:配置路由、koa-body:协议解析、@koa/cors:跨域处理
路由路径前缀设置:router.prefix(’/api’)
获取GET请求中的params: const params = ctx.request.query
每次返回请求时格式化json:koa-json

cnpm install -S koa-body @koa/cors koa-json  	// koa-body:协议解析、@koa/cors:跨域处理


const Koa = require('koa')
const Router = require('koa-router')
const koaBody = require('koa-body')
const cors = require('@koa/cors')
const json = require('koa-json')

const app = new Koa()
const router = new Router()

router.prefix('/api') //路由路径前缀设置

router.get('/', ctx => {
    console.log(ctx);
    console.log(ctx.request);
    ctx.body = 'Hello World!'
})

//获取params
router.get('/api', ctx => {
    const params = ctx.request.query

    console.log(params);
    //{ name: Heria,age: 24}
    console.log(params.name,params.age);
    ctx.body = {
        'name': params.name,
        'age': params.age
    }
})

router.post('/post', async ctx =>{
    let { body } = ctx.request
    console.log(ctx.body);
    console.log(ctx.request);
    ctx.body = {
        ...body
    }
})

app.use(koaBody())
app.use(cors())
app.use(json({pretty:false, param: 'pretty'})) // 默认关闭pretty,当传递参数(pretty)时格式化json,

app.use(router.routes()) // 把前面定义的所有的路由方法添加到app这个koa应用上去,做一个中间件处理
    .use(router.allowedMethods()) //可想象为拦截器,主要拦截应用中没有的请求,直接返回4XX或5XX

app.listen(3000)

四、工作目录,路由合并,静态资源

1.工作目录
1.1、按功能模块进行区分
1.2、路由压缩:koa-combine-routers
1.3、静态资源:koa-static
在这里插入图片描述

2.koa安全header处理

npm install -S koa-helmet 

const helmet = require('koa-helmet')
app.use(helmet())

3.静态文件引用

npm install -S koa-static

const path = require('path')
const statics = require('koa-static')
app.use(statics(path.join('__dirname','../public')))
//a.js
// function a (ctx) {
//     ctx.body = {
//         "msg": "hello from b!"
//     }
// }

// module.exports = {
//     a
// }

module.exports = function (ctx) {
    ctx.body = {
        "msg": "hello from a!"
    }
}

//b.js
module.exports = function (ctx) {
    ctx.body = {
        "msg": "hello from b!"
    }
}

//aRouter.js
const Router = require('koa-router')
const a = require('../api/a')
const router = new Router()
router.get('/a', a)
module.exports = router

//bRouter.js
const Router = require('koa-router')
const b = require('../api/b')
const router = new Router()
router.get('/b', b)
module.exports = router

//routes.js
const combineRoutes = require('koa-combine-routers')

const aroutes = require('./aRouter')
const broutes = require('./bRouter')

module.exports = combineRoutes(  //路由压缩
    aroutes,
    broutes
)

//index.js
const Koa = require('koa')
const app = new Koa()

const router = require('./routes/routes')

app.use(router())

app.listen(3000)

五、Koa配置开发热加载、ES6语法支持和webpack配置

-D和-S的本质区别:
在打包的时候会用-S安装的内容,最终打包到dist目录中,常见的axios,dayjs,这些必须用-S
-D的内容是用于开发的,比如webpack
-D对应单词dev,即开发中使用的依赖,不会打包到生产项目的包中,但是会存放在node_modules中
-S对应的单词save,即生产中使用的依赖,会打包到生产项目中,也会存放在node_modules中

1.热部署

npm install -D nodemon  // -D:开发模式,开发过程中的依赖,最终不打包进js
npx nodemon --version   // 查看nodemon版本号
./node.modules/.bin/nodemon --version //npx 相当于 ./node.modules/.bin/nodemon
npx nodemon src/index.js  // 开启热部署

在这里插入图片描述
将热部署配置为运行启动

// package.json

{
  "scripts": {
    "start": "nodemon src/index.js"
  },
}
//运行 npm run start

2.配置Webpack以使用ES6的新特性

npm install -D webpack webpack-cli
npm install -D clean-webpack-plugin webpack-node-externals @babel/core @babel/node @babel/preset-env babel-loader cross-env
//clean-webpack-plugin:清理dist目录下的一些文件
//webpack-node-externals:对node_modules下的文件做一个排除处理,这样就不会处理node_modules下的文件了
//@babel/core:babel的核心
//@babel/node:调试要用到的,在windows上要进行全局安装,否则后续会提示:“babel-node”不是内部或外部命令
//@babel/preset-env 对新特性做一下支持
//cross-env:设置环境变量

创建webpack.config.js入口文件
在这里插入图片描述

//webpack.config.js
const path = require('path')
const nodeExcternals = require('webpack-node-externals')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

debugger

const webpackconfig = {
  target: 'node',
  mode: 'development',
  entry: {
    server: path.join(__dirname, 'src/index.js')
  },
  output: {
    filename: '[name].bundle.js',
    path: path.join(__dirname, './dist')
  },
  devtool: 'eval-source-map',
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: {
          loader: 'babel-loader'
        },
        exclude: [path.join(__dirname, '/node_modules')]
      }
    ]
  },
  externals: [nodeExcternals()],
  plugins: [
    new CleanWebpackPlugin()
  ],
  node: {
    console: true,
    global: true,
    process: true,
    Buffer: true,
    __filename: true,
    __dirname: true,
    setImmediate: true,
    path: true
  }
}

console.log(webpackconfig)

module.exports = webpackconfig

新建.babelrc文件

在这里插入图片描述

//.babelrc
{
    "presets": [
        [
            "@babel/preset-env",
            {
                "targets": {
                    "node": "current"
                }
            }
        ]
    ]
}
//执行 npx webpack 打包
npx webpack
//打包后可使用ES6语法,以下是index.js文件
// const Koa = require('koa')
// const path = require('path')
import koa from 'koa'
import path from 'path'
import helmet from 'koa-helmet'
import statics from 'koa-static'
import router from './routes/routes'
const app = new koa()
// const helmet = require('koa-helmet')
// const router = require('./routes/routes')
// const statics = require('koa-static')

//使用ES6语法运行需要用到babel-node
npx babel-node src/index.js

//热部署
npx nodemon --exec babel-node src/index.js

在这里插入图片描述

出错
在这里插入图片描述
解决方法 – 版本问题
npm install webpack-dev-server@2.9.7 --save-dev
然后重装所缺少的包。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值