所以我有一个 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 提供答案。
最佳答案
如果您只是希望将响应从远程服务不加更改地传输到客户端,则可以将响应直接通过管道传输到客户端。
'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 服务器在响应客户端之前接收来自远程服务的完整响应 - 客户端开始接收远程服务响应正文一旦远程服务开始发送它。
关于node.js - 从 Node.JS 服务器应用程序中发出 GET 请求并将其发送到 React.JS 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36113616/