【发布时间】:2016-08-11 19:28:57
【问题描述】:
我来自 Express 并尝试为我正在从事的一个新项目学习 Koa2,但我正在努力让最基本的 Get 操作适用于我的应用程序。
在服务器端,我有一个访问授权服务器 (Etrade) 的路由设置,该服务器返回一个 HTML 链接,用户需要使用该链接来授权应用程序。
我可以使用 Postman 访问路由,并看到我通过我的 console.log() 调用从 Etrade 获得了链接,但它没有在响应正文中返回给 Postman。
当我将它连接到客户端应用程序时,我得到一个响应状态代码 204,这意味着如果我理解正确的话,我的响应正文是空的。
我需要弄清楚如何让响应体传递并提高我对 Koa2 的理解。
我目前将我的server.js 设置如下:
import Koa from 'koa';
import convert from 'koa-convert';
import proxy from 'koa-proxy';
import logger from 'koa-logger';
import body from 'koa-better-body';
import api from '../config/router/router';
import historyApiFallback from 'koa-connect-history-api-fallback';
import config from '../config/base.config';
const port = config.server_port;
const host = config.server_host;
const app = new Koa();
app.use(logger());
app.use(body());
app.use(api.routes());
app.use(api.allowedMethods());
// enable koa-proxyy if it has been enabled in the config
if ( config.proxy && config.proxy.enabled ) {
app.use(convert(proxy(config.proxy.options)));
}
app.use(convert(historyApiFallback({
verbose : false
})));
server.listen(port);
console.log(`Server is now running at http://${host}:${port}.`);
我的router.js 设置如下:
import Router from 'koa-router';
import etradeVerification from '../../server/api/etrade/verification';
const api = new Router({
prefix: '/api'
});
etradeVerification(api);
export default api;
最后是路由的逻辑,减去密钥和秘密的东西:
import Etrade from 'node-etrade-api';
const myKey = '';
const mySecret = '';
const configuration = {
useSandbox : true,
key : myKey,
secret : mySecret
};
const et = new Etrade(configuration);
export default function( router ) {
router.get('/etrade', getEtradeUrl);
}
async function getEtradeUrl( ctx, next ) {
// Isn't this how I send the response back to the client?
// This isn't coming through as a response body when using Postman or the client app
ctx.body = await et.getRequestToken(receiveVerificationUrl, failedToGetUrl);
}
function receiveVerificationUrl( url ) {
console.log(url); // This works and displays the response from etrade
return url
}
function failedToGetUrl( error ) {
console.log('Error encountered while attempting to retrieve a request token: ', error);
}
感谢您的帮助和指导!
【问题讨论】:
-
你好,我的body也有问题,我用的是Windows10。我无法找到此问题中引用的问题的任何解决方案;stackoverflow.com/questions/38856815/koa2-request-body-is-empty。你的操作系统是什么?
标签: javascript rest koa koa-router koa2