在KOA中最纯粹的要求

时间:2016-08-05 13:14:59

标签: javascript node.js server koa

我可能不了解JS的一些内容,但我在编写Purest响应页面正文时遇到了问题。像这里:

var koa = require('koa')
  , session = require('koa-session')
  , mount = require('koa-mount')
  , koaqs = require('koa-qs')
  , accesslog = require('koa-accesslog')
  , router = require('koa-router')()
  , app = koa();

var Grant = require('grant-koa')
  , grant = new Grant(require('./config.json'))

app.keys = ['grant']
app.use(accesslog())
   .use(session(app))
   .use(mount(grant))
   .use(router.routes())
   .use(router.allowedMethods());
koaqs(app)

router.get('/handle_facebook_callback', function *(next) {
  getProfile(this.query.access_token);
	
})

var config = {
  "facebook": {
    "https://graph.facebook.com": {
      "__domain": {
        "auth": {
          "auth": {"bearer": "[0]"}
        }
      },
      "{endpoint}": {
        "__path": {
          "alias": "__default"
        }
      }
    }
  }
}

var request = require('request')
  , purest = require('purest')({request})
  , facebook = purest({provider: 'facebook', config})

function getProfile(access_token, responseToBody){
	facebook.get('me')
            .auth(access_token)
			.request(function (err, res, body) {
				this.body=JSON.stringify(body,null,2);
  })
}


if (!module.parent) app.listen(3000);
console.log('oh!GG is running on http://localhost:3000/');

我会假设在facebook.request函数中“this.body = JSON.stringify(body,null,2);”部分应该将反应写入身体,但事实并非如此。 究竟是什么问题?

1 个答案:

答案 0 :(得分:3)

路线(发电机)不等待getProfile完成。您需要yield

现在在你的代码片段中,它执行getProfile,它立即返回到生成器,生成器完成,Koa看到你没有设置this.body,因此它默认为404响应。

一旦getProfile中的回调最终在某个时间点触发,响应已经发送并且您收到错误。

使用回调式函数与Koa一起工作的一般解决方案(即使它可以yield它)将它包装在Promise中:

function getProfile (access_token) {
  return new Promise(function (resolve, reject) {
    facebook.get('me')
      .auth(access_token)
      .request(function (err, res, body) {
        if (err) return reject(err)
        resolve(body)
      })
  })
}

router.get('/handle_facebook_callback', function * (next) {
  const profile = yield getProfile(this.query.access_token)
  this.type = 'application/json'
  this.body = JSON.stringify(profile, null, 2)
})

getProfile现在返回一个你可以屈服的Promise。

另外,请注意我更改了它,以便getProfile使用配置文件对象解析,而Koa处理程序是将this.body和JSON拼接在一起的处理程序。

这通常是你想要在Koa中做事的方式,这样你的所有响应变异都会在一个地方的处理程序内发生。