koa2

koa2请求返回数据404

北战南征 提交于 2020-01-21 17:17:55
用koa2写了个register的post请求,后端确实收到了参数,也写入数据库了,但是返回给前端的时候出了问题,前端报404拿不到返回的数据。具体原因跟koa2的异步请求有关,async await返回的是异步结果,所以在post回掉函数内也要用异步获取数据返回,否则同步获取是拿不到数据的,前端也就显示404了 具体代码就贴一下,大家可以参考下: const fnRegister = async (ctx, next) => { const { username, password } = ctx.request.body; // 查询用户是否存在 const userResult = await UserModel.find({username}); if (userResult.length) { ctx.body = { code: 1, msg: '用户名已存在' }; return; } // 写入mongoDB const User = new UserModel({ username, password }); await User.save().then(() => { return ctx.body = { code: 0, msg: '注册成功' } }).catch((error) => { return ctx.body = { code: 1, msg:

Koa2: how to write chain of middleware?

半世苍凉 提交于 2020-01-02 10:04:42
问题 So in express, we can have a chain of middleware, copies an example: middleware = function(req, res){ res.send('GET request to homepage'); }); app.get('/', middleware, function (req, res) { res.send('GET request to homepage'); }); What's the equivalent way to write this in koa2 please ? I'm thinking of using it for the route, for each route i want to have a middleware to check if user is already logged in. Thanks ! 回答1: If you're simply interested in making sure a middlware runs for every

Koa2源码阅读笔记

别说谁变了你拦得住时间么 提交于 2019-12-31 17:21:38
引言 最近空闲时间读了一下 Koa2 的源码;在阅读Koa2(version 2.2.0)的源码的过程中,我的感受是代码简洁、思路清晰(不得不佩服大神的水平)。 下面是我读完之后的一些感受。 Koa的设计理念 Koa 是一个轻量级的、极富表现力的 http 框架。 一个web request会通过 Koa 的中间件栈,来动态完成 response 的处理。 Koa2 采用了 async 和 await 的语法来增强中间件的表现力。 Koa 不在内核方法中绑定任何中间件,它仅仅提供了一个轻量优雅的函数库。 Koa基本组成 Koa源码非常精简,只有四个文件: application.js:框架入口;负责管理中间件,以及处理请求 context.js:context对象的原型,代理request与response对象上的方法和属性 request.js:request对象的原型,提供请求相关的方法和属性 response.js:response对象的原型,提供响应相关的方法和属性 application.js // application.js module.exports = class Application extends Emitter { constructor() { super(); this.proxy = false; // 是否信任 proxy header 参数

What's the recommend code for koa-ejs using koa2?

﹥>﹥吖頭↗ 提交于 2019-12-25 07:41:42
问题 I planed use ejs in koa2, my codes were like as blelow: render(app, { root: path.join(__dirname, 'views-ejs'), layout: 'layout', viewExt: 'ejs', cache: false, debug: true }); app.use(function *() { yield this.render('index',{ title: 'koa2 title', viewClass: 'landing', targetAuthLevel:'', authorizationLevel:'6', ngController: 'landingController' }); }); But, I get the below warning, would you tell me what's codes are recommended? please. koa deprecated Support for generators will been removed

Node.js 应用:Koa2 使用 JWT 进行鉴权

删除回忆录丶 提交于 2019-12-20 18:08:48
前言 在前后端分离的开发中,通过 Restful API 进行数据交互时,如果没有对 API 进行保护,那么别人就可以很容易地获取并调用这些 API 进行操作。那么服务器端要如何进行鉴权呢? Json Web Token 简称为 JWT,它定义了一种用于简洁、自包含的用于通信双方之间以 JSON 对象的形式安全传递信息的方法。JWT 可以使用 HMAC 算法或者是 RSA 的公钥密钥对进行签名。 说得好像跟真的一样,那么到底要怎么进行认证呢? 首先用户登录时,输入用户名和密码后请求服务器登录接口,服务器验证用户名密码正确后,生成token并返回给前端,前端存储token,并在后面的请求中把token带在请求头中传给服务器,服务器验证token有效,返回正确数据。 既然服务器端使用 Koa2 框架进行开发,除了要使用到 jsonwebtoken 库之外,还要使用一个 koa-jwt 中间件,该中间件针对 Koa 对 jsonwebtoken 进行了封装,使用起来更加方便。下面就来看看是如何使用的。 生成token 这里注册了个 /login 的路由,用于用户登录时获取token。 const router = require('koa-router')(); const jwt = require('jsonwebtoken'); const userModel = require(

koa2入门学习

只谈情不闲聊 提交于 2019-12-18 01:26:23
koa模块 koa-route 路由 route.get("路径",路由函数) koa-static 静态资源加载 const serve(路径) koa-compose 中间件合成模块 koa-body 提取表单post请求键值对,处理上传文件 上下文context的response和request ctx.response.body   //返回的主体内容 ctx.response.redirect //重定向 ctx.response.type   //返回的MIME类型 ctx.response.path  //获取用户请求的路径 ctx.response.status //返回的状态码 ctx.request.accepts //请求的mime类型 ctx.request.method //请求的方法 ctx.request.url //请求的url ctx .request .body //请求的body 中间件(middleware) Logger 打印日志 //不需要引入任何,直接输入console.log,在命令框就会打印出来 中间件功能可以拆分成一个独立函数比如叫logger,参数(ctx,next) 然后app.use(logger),用来加载中间件 基本上,Koa 所有的功能都是通过中间件实现的,前面例子里面的main也是中间件。 每个中间件默认接受两个参数

Koa-compress is not working

无人久伴 提交于 2019-12-12 03:27:17
问题 This is my code for embedding koa-compress middleware app.use(compress({ filter: function (content_type) { return /text/i.test(content_type) }, threshold: 1, flush: require('zlib').Z_SYNC_FLUSH })) And following is my response sending code ctx.body = 'Hello world' ctx.compress = true ctx.set('Content-Type', 'text/plain') ctx.set('content-encoding', 'gzip') When I hit the URL through CURL I get a simple plain text saying "Hello World" but I believe I should have I got a compressed string

Unable to send authenticated request in tests using Jest, Supertest, Passport, Koa2

孤街浪徒 提交于 2019-12-11 16:19:31
问题 Despite my best attempts to correctly write test code to authenticate a request agent in Setup blocks or previous describe/it blocks, any request I make from the agent in subsequent describe/it blocks never completes as 200. Example code: const request = require('supertest'); const server = require('../server'); let agent = request.agent(server); let fakePerson = null; beforeEach(async (done) => { fakePerson = await Person.createMock(); agent.post(‘/login’) .send({ email: ‘test@user.com’,

Getting entity's id inside a transaction

别等时光非礼了梦想. 提交于 2019-12-11 03:47:46
问题 I have a datastore transaction where I create an entity (a user) letting datastore generate the ID for me. I then would like to use that ID so that I can create another entity (of another kind). While this is possible with regular datastore 'save' api: datastore.save(user).then(() => { userId = user.key.id // returns entity's ID created by datastore }) However, this does not seem possible when using a transaction: transaction.save(user).then(() => { console.log( user.key.id ) }) The above

Error handling in async await

ぃ、小莉子 提交于 2019-12-10 17:44:21
问题 How can you implement error handling for Mongoose (current version v5.1.5)? For example, let's assume the following code where a user detail is being looked up. let u = await user.find({ code: id }).lean(); return u; And some error occurs, how should it be handled? Secondly, can we have centralised error handling function which will get triggered whenever an error happens in any of the Mongoose code, it gets directed to a particular function in the project where it can be handled. 回答1: You