javascript - 将 HTTP 响应写入页面显示为纯文本

标签 javascript node.js http httpresponse

我正在转发从代理服务器发出的请求并在浏览器中呈现响应。但是,当我使用 res.write(data) 呈现响应时,它以纯文本而不是呈现的 html 形式出现:

http.createServer(function targetServer(req, res) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    var request = http.request('http://www.google.com', function(res) {
        var body = '';
        response.on('data', function(chunk) {
            body += chunk;
        });
        response.on('end', function() {
            fs.writeFile('res.txt', body, {encoding:'utf8'}, function() {
                util.puts('Success!');

            });
            res.write(body);
        });
    });
    request.end();  
});

res.txt 的内容是:

<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for." name="description"><meta content="noodp" name="robots"><meta content="/images/google_favicon_128.png" itemprop="image"><title>Google</title>
<!-- other html -->
</html>

但它不像 google.com 那样呈现,它看起来像 res.txt 文件:

<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for." name="description"><meta content="noodp" name="robots"><meta content="/images/google_favicon_128.png" itemprop="image"><title>Google</title>
<!-- other html -->
</html>

有人可以向我解释我做错了什么吗?

更新

将内容类型更改为 text/html 后,我现在在浏览器中收到错误消息:

The character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature.

这是关于什么的?

最佳答案

尝试:

res.writeHead(200, { 'Content-Type': 'text/html' });

然后:

response.setEncoding('utf8');
response.on('data', function(chunk) {
    body += chunk;
});

关于javascript - 将 HTTP 响应写入页面显示为纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26319170/

相关文章:

javascript - Angular $http.get 不传递参数

node.js - 如何对通过管道 readStream 传递的内容进行 gZip

node.js - NodeJS 中的 Bootstrap 模态窗口

javascript - Node.js client.emit 仅在第一次尝试后才工作?

Swift 3 - 为 HTTP 调用创建可重用的类

http - 为什么推荐使用ctx作为第一个参数?

c# - 如何在 HttpRequestMessage 中包含 If-None-Match header

javascript - 按数据属性过滤对象并在每次使用时重置过滤器

javascript - HTML 表格中单元格的工具提示(无 Javascript)

javascript - 表排序器不正确