node.js - 解决koa-router无法返回异步获取mongo数据问题

【字号: 日期:2022-09-29浏览:33作者:雯心

问题描述

//koaServer.jsvar koa = require(’koa’);var logger = require(’koa-logger’);var router = require(’koa-router’)();var cors = require(’koa-cors’);var app = new koa();//日志文件app.use(logger());//一键搞定跨域app.use(cors());router.get(’/video’, function*(next) {this.body = yield koaConnection(function (data) { return data;});yield next; });app.use(router.routes()).use(router.allowedMethods());app.listen(3000, () => { console.log(’koa start!’);});

koaConnection封装了mongodb驱动,data是mongo查询后返回的结果。前端页面测试/video接口返回错误:Fetch API cannot load http://localhost:3000/video. No ’Access-Control-Allow-Origin’ header is present on the requested resource. Origin ’http://localhost:8888’ is therefore not allowed access. The response had HTTP status code 500. If an opaque response serves your needs, set the request’s mode to ’no-cors’ to fetch the resource with CORS disabled.

这里应该是我用错了方法,调用接口后,this.body第一次什么都没拿到就返回了。所以前端接口报了500错误。

第一次接触koa和mongo,还不太懂generator函数,望大牛指点。最简单的需求,不管用回调,Promise,Genrator,Async还是co,能正确返回数据就好。

thx

----------------------------分割线----------------------------

想想可能是异步的问题,所以改写了下:

router.get(’/video’, function*(next) {this.body = yield new Promise(function (resolve, reject) { koaConnection(function (data) {resolve(data); });}).then(function (data) { return data;}); // yield next; }

用Promise封装了下。测试接口返回了想要的结果。

于是(瞎猫碰到死耗子)混杂用Generator,Promise和回调函数搞定了需求。但是我搞不懂函数的运行逻辑。再次求大神指点。

thx

问题解答

回答1:

前端报错是因为你跨域的部分没处理对,koa-cors配置得搞下。

相关文章: