所以我有一个Koa / Node JS简单后端,它只是为了向外部API发出GET请求,然后将响应主体传递给我构建的React JS客户端应用程序。我是Koa或任何Node 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的答案。
答案 0 :(得分:1)
如果您只想将远程服务的响应漏报给客户端,则可以将响应直接传送给客户端。
'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'));
在这种情况下管道的一个好处是客户端不必等待node.js服务器在响应客户端之前从远程服务接收完整响应 - 客户端开始接收远程服务响应正文一旦远程服务开始发送它。