我正在转发从代理服务器发出的请求并在浏览器中呈现响应。但是,当我使用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.
这是关于什么的?
答案 0 :(得分:1)
尝试:
res.writeHead(200, { 'Content-Type': 'text/html' });
然后:
response.setEncoding('utf8');
response.on('data', function(chunk) {
body += chunk;
});