【问题标题】:How to download, modify and serve distant page如何下载、修改和提供远程页面
【发布时间】:2018-11-10 10:39:45
【问题描述】:

我尝试创建一个 http 服务器,它将在 https://google.com 下载 HTML 并提供它(在 localhost:3000)。一种代理。

使用此代码:

const express = require('express')
const https = require('https')

const app = express()

app.get('/', function (req, mainRes) {
    https.get('https://www.google.fr', (res) => {
        res.on('data', (d) => {
            mainRes.send(d)
        })
    })
})

app.listen(3000)

google.com 的 html 似乎已下载,但服务器因此错误而崩溃:

Error: Can't set headers after they are sent.

我知道这与 2 个打包的请求有关,但我不知道如何解决。

【问题讨论】:

    标签: node.js express https http-proxy


    【解决方案1】:

    @sdgluck && @kwesi1337 帮我找到了解决方案,我需要连接 data 事件中的所有块:

    const express = require('express')
    const https = require('https')
    
    const app = express()
    let data = ''
    
    app.get('/', function (req, mainRes) {
        https.get('https://www.google.fr', (res) => {
            res.on('data', (chunk) => {
                data += chunk;
            })
            res.on('end', () => {
                mainRes.end(data);
            });
        })
    })
    
    app.listen(3000)
    

    【讨论】:

      【解决方案2】:

      在您的代码中,参数res 是一个流(请参阅https.get 的文档)。

      目前,您正在尝试在每次通过该流接收到块时发送完整的响应。因此,您收到错误Can't set headers after they are sent.,因为第二次调用mainRes.send(),您正试图再次发送整个响应。 (请参阅 express 的文档'res.send。)

      您想通过快速响应对象通过管道传递res,因为这也是一个流:

      const express = require('express')
      const https = require('https')
      
      const app = express()
      
      app.get('/', function (req, mainRes) {
          https.get('https://www.google.fr', (res) => {
              mainRes.pipe(res)
          })
      })
      
      app.listen(3000)
      

      【讨论】:

      • 谢谢,没有错误了,但是这个 sn-p 似乎没有返回任何东西,并且 localhost:3000 在超时之前一直在旋转。另外,如果我想修改 google.com 的 html 怎么办?再次感谢
      【解决方案3】:

      我不是 100% 确定您的情况,但我建议您添加调试器语句并逐步执行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-05
        • 2012-02-09
        • 2016-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多