从Node.JS服务器应用程序中发出GET请求,并将其发送到React.JS客户端

所以我有一个Koa / Node JS简单的后端,只是为了向外部API发出一个GET请求,然后将响应体传递给我正在构build的React JS客户端应用程序。 我是Koa或任何节点的JS或服务器的新手,所以不能真正弄清楚如何。

像这样的东西:

var koa = require('koa'); var app = koa(); app.use(function *(){ http.get({host: somehost, path: somepath}, function(response) { this.body = Here send to React Client } ) }); app.listen(3000); 

编辑:使用ExpressJS的答案也是受欢迎的。

如果您只是希望将远程服务的响应从客户端转移到客户端,则可以将响应直接传递给客户端。

 'use strict' const express = require('express'); const http = require('http'); const app = express(); app.use("/test", (clientRequest, clientResponse) => { http.get('http://some-remote-service.com', (remoteResponse) => { // include content type from remote service in response to client clientResponse.set('Content-Type', remoteResponse.headers['content-type']); // pipe response body from remote service to client remoteResponse.pipe(clientResponse); }); }); app.listen(3000,() => console.log('server started')); 

在这种情况下pipe道的一个好处是,客户端不必等待node.js服务器在响应客户端之前从远程服务接收完整响应 – 客户端尽快接收远程服务响应主体远程服务开始发送它。