我来自 Express 并试图为我正在从事的一个新项目学习 Koa2,但我正在努力让最基本的 Get 操作为我的应用程序工作。
在服务器端,我有一个访问授权服务器 (Etrade) 的路由设置,它返回一个 HTML 链接,用户需要使用该链接来授权应用程序。
我可以使用 Postman 访问路由,并看到我通过调用从 Etrade 获得了链接console.log()
,但它没有在响应正文中返回给 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);
}
感谢您的帮助和指导!