Proxing请求远程服务器

时间:2017-03-17 11:13:01

标签: angularjs node.js express

我试图通过express.js代理来自我的角度客户端应用程序的请求。这是中间件

app.use('/v1', function(req, res) {  
  var url = process.env.API_URL + req.url;
  console.info('Proxing to: ', url);

  var r = null;

  switch(req.method) {
      case 'POST':
        r = request.post({uri: url, json: req.body });
        break;
      case 'PUT':
        r = request.put({uri: url, json: req.body });
        break;

      default:
        r = request(url);
  }  

  console.log(r);

  return req.pipe(r).pipe(res);
});

快递服务器正在http://localhost:3030运行。中间件适用于http://localhost:3030/v1的GET请求,但它不适用于POST或PUT请求。 当我发出PUT或POST请求时,服务器被终止。这是错误

stream.js:74
      throw er; // Unhandled stream error in pipe.
      ^

Error: write after end
    at ClientRequest.OutgoingMessage.write (_http_outgoing.js:426:15)
    at Request.write (/Users/user/Projects/maxmc/node_modules/request/request.js:1514:27)
    at end (/Users/user/Projects/maxmc/node_modules/request/request.js:552:18)
    at Immediate._onImmediate (/Users/user/Projects/maxmc/node_modules/request/request.js:581:7)
    at tryOnImmediate (timers.js:543:15)
    at processImmediate [as _immediateCallback] (timers.js:523:5)
error Command failed with exit code 1.

我无法确定问题所在。

2 个答案:

答案 0 :(得分:0)

尝试使用以下代码

app.use('/v1', function(req, res) {
  var url = process.env.API_URL + req.url;
  console.info('Proxing to: ', url);

  var r = null;

  switch (req.method) {
    case 'POST':
      r = request.post({
        uri: url,
        json: req.body
      });
      return req.pipe(r).pipe(res);
    case 'PUT':
      r = request.put({
        uri: url,
        json: req.body
      });
      return req.pipe(r).pipe(res);

    default:
      r = request(url);
      return req.pipe(r).pipe(res);
  }

  //console.log(r);

  //return req.pipe(r).pipe(res);
});

尝试使用此代码

答案 1 :(得分:0)

删除bodyParser中间件修复此

//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({ extended: true }));