2016-04-24 2 views
0

私はkoaとkoa-routerでREST APIを設定しました。私はAPIのエンドポイントとconsole.log(ctx.body)を打つことができ、私は見たいと思うものを見ている。この場合、私はURLでJSONオブジェクトを見ることを期待し、それは私がそれを慰めるときに私はノード側に表示されるものです。Koa2とkoa-routerを使用してReactクライアントにREST APIのGET応答を送信するにはどうすればよいですか?

etrade_api: { oauth_token: 'hidden', 
oauth_token_secret: 'hidden', 
authorizeUrl: 'https://us.etrade.com/e/t/etws/authorize?key=hidden&token=hidden' } 

しかし、私が反応して、エンドポイントを消費しようとすると、私は、クライアント上で取得しています応答は以下のようになります。Responseオブジェクト:

Response {url: "http://localhost:3000/api/verification", status: 200, statusText: "OK", headers: Headers, ok: true…} 
_abort:false 
_raw:Array[0] 
body:PassThrough 
bodyUsed:false 
headers:Headers 
ok:true 
size:0 
status:200 
statusText:"OK" 
timeout:0 
url:"http://localhost:3000/api/verification" 
__proto__:Body 

私の質問です私は上記のクライアント上の私のノードにconsole.logに期待されるJSONオブジェクトを得るのですか?

私は非常に新しいので、彼らは残りの部分を設定する方法の他の人の例に従うことによってそれを学ぶことを試みている。現在、私のサーバーは、次のようになります。

import Koa from 'koa'; 
import convert from 'koa-convert'; 
import historyApiFallback from 'koa-connect-history-api-fallback'; 
import serve from 'koa-static'; 
import body from 'koa-better-body'; 
import error from 'koa-error'; 
import compress from 'koa-compress'; 
import session from 'koa-session'; 
import responseTime from 'koa-response-time'; 
import logger from 'koa-logger'; 
import config from '../settings/config'; 
import routes from './api/router/routes'; 


const paths = config.utils_paths; 
const app = new Koa(); 

app.keys = ['somethin up in here']; 

app.use(responseTime()); 
app.use(error()); 
app.use(logger()); 
app.use(convert(session(app))); 

// Setup api routes 
app.use(body()); 
routes(app); 

// This rewrites all routes requests to the root /index.html file 
// (ignoring file requests). If you want to implement isomorphic 
// rendering, you'll want to remove this middleware. 
app.use(convert(historyApiFallback({ 
    verbose: false 
}))); 

app.use(convert(serve(paths.client('static')))); 
app.use(compress()); 
app.listen(3000); 

そして、私のルート・ファイルには次のようになります取るため

import etApi from '../etrade_api'; 

export default function(router){ 
    router.get('/verification', getEtradeVerificationLink); 
    // other routes here 
} 

async function getEtradeVerificationLink(ctx, next) { 
    const myKey = 'hidden'; 
    const mySecret = 'hidden'; 

    try { 
     ctx.body = await etApi.requestToken(myKey, mySecret); 
     console.log('etrade_api:', ctx.body); // this prints out what I expect to see 
    } 
    catch (error) { 
     console.error('Failed to get verification link.', error); 
    } 
} 

ありがとう:

import Router from 'koa-router'; 
import account_routes from '../accounts'; //import controllers 

export default function (app) { 
    const router = new Router({ 
     prefix: '/api' 
    }); 

    account_routes(router); 

    app.use(router.routes()); 
    app.use(router.allowedMethods()); 
} 

は、最後に私のコントローラは、以下のようになります。これを見て、できる限りの助けを提供してください。

+0

コマンドラインから 'curl -i http:// localhost:3000/api/verification'を試したことがありますか?これにより、サーバーがエラーの原因であることを確認できます。 – pe8ter

+0

以前はcurlを使用していませんでしたが、それをインストールしてコマンドを適用しました。 apiが動作しているように見えます。私は、私が期待したキーとデータでヘッダとオブジェクトを取り戻しました。ヘッダーには、 HTTP/1.1 200 OK コンテンツタイプ:application/json;文字セット= UTF-8 X-応答時間:306ms のContent-Length:280 日:今日 接続:キープアライブ {ここで私の期待オブジェクト}興亜は、問題ではないようにむしろ – Zigrivers

+0

は、サウンドAPIを呼び出すクライアントサイドのコード。 – pe8ter

答えて

0

@ pe8terは私を正しい道に導いた。私のサーバー側のコードに問題はなかったことが分かりました。クライアント側のコードでした。私はAPIを消費するためにフェッチを使用していましたが、フェッチが正しく返されるという約束を処理していませんでした。

export function fetchVerificationLink() { 
    return async(dispatch) => { 
     dispatch(requestVerificationLink()); 

     let response, link; 
     try { 
      response = await read(urls.etradeVerification); // I have a wrapper around node-fetch, but failed to handle the promise that fetch returns 

      dispatch(receiveVerificationLink(response)); 
     } 
     catch (error) { 
      console.error('Unable to get verification link from eTrade.', error); 
     } 
    } 
} 

私はからの応答を処理するために、これにコードを変更フェッチ::私が行うために必要なすべてはここから私のクライアント側のコードを変更した

export function fetchVerificationLink() { 
    return async(dispatch) => { 
     dispatch(requestVerificationLink()); 

     let response, link; 
     try { 
      response = await read(urls.etradeVerification); 
      try { 
       link = await response.json(); // Here was the solution to my problem. 
       dispatch(receiveVerificationLink(link)); 
      } 
      catch (error) { 
       console.error('Unable to parse authorization link response.', error); 
      }     
     } 
     catch (error) { 
      console.error('Unable to get verification link from eTrade.', error); 
     } 
    } 
} 

そして今、すべてが期待通りに働いています。助けてくれてありがとう!

関連する問題