为了账号安全,请及时绑定邮箱和手机立即绑定

入门基于node平台的web开发框架koa(1)

标签:
Node.js

我相信学习前端的小伙伴们一直都有一个困扰:只会前端并没有办法操作数据库从而开发一个完整的项目-全栈开发,操作数据库等服务端开发一直都是前端开发者的软肋,想要去学习一门如php或是java的后端语言又太费时费力,那难道就没有办法了吗?答案是有的,node.js的出现让前端开发的世界更加的广阔,让前端不在局限于客户端。而今天就来和大家介绍一下能让前端快速上手后端服务的框架-koa。

koa是一个新的web框架,致力于成为web应用和API开发领域中的一个更小、更富有表现力、更健壮的基石。

利用async函数丢弃回调函数,并增强错误处理。koa没有任何预置的中间件,可快速而愉快地编写服务端应用程序。

进入到开发目录:E:\exercise\2021\koaStudent

通过 npm init -y  初始化创建package.json文件,其中

https://img1.sycdn.imooc.com//60668b0b0001707e07570331.jpg

通过 npm install --save koa

https://img1.sycdn.imooc.com//60668b29000181c707430293.jpghttps://img1.sycdn.imooc.com//60668b400001975a07720296.jpg

通过 npm install -s koa-router // 路由处理插件

npm install @koa/cors@2 --save // 处理跨域问题

npm install koa-body // 上传下载文件

npm install -s koa-json // 处理数据格式

npm install koa koa-router koa-body @koa/cors koa-json -s // 可以连起来执行

https://img1.sycdn.imooc.com//60668e7d0001742805690220.jpg

const Koa = require('koa')const Router = require('koa-router') // 引入路由插件
const cors = require('@koa/cors') // 处理是跨域const koaBody = require('koa-body') // 处理上传下载文件
const app = new Koa()
const router = new Router()
// ctx 上下文
//1.request(请求) 2.method(方法) 3.respond(回应)
// async 异步请求结果
/** 
* app.use(function)  将给定的中间件方法添加到此应用程序。app.use() 返回 this, 因此可以链式表达 
* 每当Koa收到一个HTTP请求时,会调用通过app.use()注册的async异步函数并传入ctx和next参数。
可以针对ctx进行操作并设置返回内容。
app.use(async ctx => {  console.log(ctx)  ctx.body = 'Hello'}) 
*/
// router.prefix('api') 设置接口前缀
router.get('/', ctx => {  
    console.log(ctx)  
    ctx.body = ctx.request
  })
router.get('/text', ctx => {  
    console.log(ctx)  
    const params = ctx.request.query  
    ctx.body = {    
        ...params,
        testContent: '测试内容'  
      }})
router.get('/student', ctx => {  
    console.log(ctx)  
    ctx.body = 'student'
  })
/** * router.allowedMethods 为拦截器,拦截应用中没有的请求 * */
router.post('/post2', ctx => {  
    console.log(ctx)  
    let { body } = ctx.request  
    console.log(body)  
    ctx.body = {    
        ...body  
        }
      })
 router.post('/post', async (ctx) => {  
     console.log(ctx)  
     let { body } = ctx.request  
     console.log(body)  
     ctx.body = {    
         ...body  
       }
     })
 app.use(koaBody()) // 使用post请求内容时
 app.use(router.routes()).use(router.allowedMethods())
 app.listen(3000)

https://img1.sycdn.imooc.com//60668e3b00018f5914830715.jpg

点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
Web前端工程师
手记
粉丝
76
获赞与收藏
534

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消