【问题标题】:Make a GET request from within a Node.JS server app and send it to React.JS client从 Node.JS 服务器应用程序中发出 GET 请求并将其发送到 React.JS 客户端
【发布时间】:2016-03-20 12:20:18
【问题描述】:

所以我有一个 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 回答。

【问题讨论】:

标签: node.js reactjs get request koa


【解决方案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 服务器在响应客户端之前从远程服务接收到完整响应 - 客户端开始接收远程服务响应正文只要远程服务开始发送它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多