【问题标题】:Node translation > client > node > json > node > client节点翻译 > 客户端 > 节点 > json > 节点 > 客户端
【发布时间】:2018-04-27 20:35:19
【问题描述】:

我的节点不太好,需要你的帮助。

我想让我的节点成为“翻译器”。什么意思?

我发现了这样的东西: How to forward a request to other endpoint in node.js

我想通过ajax请求发送到我的节点服务器,然后这个服务器应该发送请求到json并在浏览器中显示接收到的数据。

如何更改它以接收响应并将其发送到浏览器?

var express = require('express');
var fs = require('fs');
var path = require('path');
var http = require('http');
var https = require('https');
var app = express();

var HTTP_PORT = 3000;

// Create an HTTP service
http.createServer(app).listen(HTTP_PORT,function() {
  console.log('Listening HTTP on port ' + HTTP_PORT);
});


//endpoint for tracking
app.get('/track', function(req, res) {

  sendRequestToOtherEndPoint(req);

  processRequest(req);
  res.setHeader('Content-Type', 'application/json');
  res.send('Req OK');
});

function processRequest(req){
    console.log("request processed");
}

function sendRequestToOtherEndPoint(req){
    //magic here :)
}

我花了很多时间,但没有想法。

我的 ajax 请求:

<script type="text/javascript">
$(document).ready(function() {
    $("#testbutton").click(function() {
        $.ajax({
url: '',
            dataType: 'json',
            success: function(data) {
                $("#results").append('works');
                alert(data);
            },
             error: function() {
                $("#results").append("error");
                alert('error');
            }
        });
    });
});
</script>

我的实际服务器只包含

  request({
      url: ,
      method: "GET",
      timeout: 10000,
      followRedirect: true,
      maxRedirects: 10
  },function(error, response, body){
      if(!error && response.statusCode == 200){
          console.log('sucess!');
           console.log(response.body);
      }else{
          console.log('error' + response.body);
      }

并在开始时听 + 一些变量。

【问题讨论】:

    标签: json node.js ajax


    【解决方案1】:

    因此,您要查找的术语是“反向代理”。有很多方法可以做到这一点,也有很多潜在的陷阱,但如果你不想使用像 reverse-proxy 这样的现有模块,那么你可能想要做的是使用 request 模块到pipe the request and response streams。像这样的:

    app.get('/proxy', (req, res) => {
      request('http://example.com/').pipe(res);
    });
    

    【讨论】:

      猜你喜欢
      • 2017-11-17
      • 1970-01-01
      • 2014-04-10
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      相关资源
      最近更新 更多