我想接受一个请求,将它转发到另一个url并返回forwared请求的结果.
这是我的代码:
const http = require('http'), server = http.createServer().listen(3000); const baseUrl = 'foo.bar'; server.on('request', (req, res) => { req.headers.host = baseUrl; var connector = http.request(req, (resp) => { resp.pipe(res); }); req.pipe(connector); });
可悲的是,我收到错误,插座挂断了.
Error: socket hang up at createHangUpError (_http_client.js:203:15) at Socket.socketOnEnd (_http_client.js:288:23) at emitNone (events.js:72:20) at Socket.emit (events.js:166:7) at endReadableNT (_stream_readable.js:903:12) at doNTCallback2 (node.js:439:9) at process._tickCallback (node.js:353:17)
有谁知道,我做错了什么?
尝试手动配置新请求对象,不要更改req
对象.
这有效:
const http = require('http'), server = http.createServer().listen(3000); const baseUrl = 'www.i.ua'; server.on('request', (req, res) => { var connector = http.request({ host: baseUrl, path:'/', method: 'GET', headers: req.headers }, (resp) => { resp.pipe(res); }); req.pipe(connector); });
所以,你应该有这样的事情:
const http = require('http'), server = http.createServer().listen(3000); const baseUrl = 'radio.i.ua'; server.on('request', (req, res) => { var connector = http.request({ host: baseUrl, path: req.url, method: req.method, headers: req.headers }, (resp) => { resp.pipe(res); }); req.pipe(connector); });