Javascript Nodejs:如何以相同的响应(文本和图像)返回不同的内容类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14886161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:13:54  来源:igfitidea点击:

Nodejs: How return different content types with same response (text and image)?

javascriptnode.js

提问by xdl

I'm trying to learn nodejs and I thought the best way to do this would be to try doing some stuff without using express or any other non-core modules. I'm stuck on trying to get some text and an image to be delivered simultaneously. The code I'm trying is:

我正在尝试学习 nodejs,我认为最好的方法是尝试在不使用 express 或任何其他非核心模块的情况下做一些事情。我一直在尝试同时发送一些文本和图像。我正在尝试的代码是:

var http = require('http');
var fs = require('fs');

var server = http.createServer(function(request,response) {

    fs.readFile('my_pic.jpg', function(error, file) {
        response.writeHead(200, {'content-type':'text/html'});
        response.write('<p>hi there!</p>');

        response.writeHead(200, {'content-type':'image/jpg'});
        response.write(file, 'image');

        response.end();
    });

});

var port = process.env.PORT || 8080;

server.listen(port, function() {
    console.log('Listening on port ' + port);
});

So ideally what should be delivered is:

所以理想情况下应该交付的是:

<html>
<body>
<p>hi there</p>
<img src='my_pic.jpg'/>
</body>
</html>

But instead, nothing is appearing.

但相反,什么也没有出现。

I tried putting a response.end() after writing 'hi there', which displays the text, and after that I tried swapping the places of the text and picture (headers included), which displayed the picture, but I can't figure out how to get both to display simultaneously, like on a real web page.

我尝试在写下“hi there”后放置一个 response.end(),显示文本,然后我尝试交换显示图片的文本和图片(包括标题)的位置,但我想不通了解如何让两者同时显示,就像在真实的网页上一样。

Can you explain how to go about putting in different types of content onto the same webpage - do they need to be in different responses? Something I came across on another question:

你能解释一下如何将不同类型的内容放到同一个网页上——它们需要有不同的响应吗?我在另一个问题上遇到的事情:

nodejs - How to read and output jpg image?

nodejs - 如何读取和输出 jpg 图像?

Something like that looks like the solution, but I can't figure out how to apply this to my situation (I don't have a lot of experience in the server side of things.)

类似的东西看起来像解决方案,但我不知道如何将它应用于我的情况(我在服务器端没有很多经验。)

Many thanks

非常感谢

EDIT: got it working from user568109's reply:

编辑:从 user568109 的回复中得到它的工作:

var http = require('http');
var fs = require('fs');


var server = http.createServer(function(request,response) {
fs.readFile('my_pic.jpg', function(error, file) {

    var imagedata = new Buffer(file).toString('base64');

    response.writeHead(200, {'content-type':'text/html'});
    response.write("hi there!<img src='data:my_pic.jpg;base64,"+imagedata+"'/>");
    response.end();

    });

});

var port = process.env.PORT || 8080;

server.listen(port, function() {
    console.log('Listening on port' + port);
});

This seems like a lot of work in embedding images though - if I wanted to put more than one image in, I'd have to just keep nesting those filestream callbacks?

不过,这在嵌入图像方面似乎有很多工作 - 如果我想放入多个图像,我必须继续嵌套这些文件流回调吗?

I also tried it this way but it doesn't work:

我也试过这种方式,但它不起作用:

var http = require('http');
var fs = require('fs');

var server = http.createServer(function(request,response) {

    response.writeHead(200, {'content-type':'text/html'});
    response.write("hi there!<img src='my_pic.jpg'/>");
    response.end();

});

var port = process.env.PORT || 8080;

server.listen(port, function() {
    console.log('Listening on port' + port);
});

I wasn't sure if this was what people meant by the line

我不确定这是否是人们所说的意思

response.write('<img src="my_pic.jpg"/>')

, because the server doesn't seem to be making another request on my behalf to go fetch the image? It's just showing a broken icon image.

,因为服务器似乎没有代表我发出另一个请求来获取图像?它只是显示一个损坏的图标图像。

采纳答案by user568109

If you do response.write('<img src="my_pic.jpg"/>');as mentioned above the image file would be sent only when browser sends GET for the image. It would become multi-part request.

如果您response.write('<img src="my_pic.jpg"/>');按照上述方式进行操作,则仅当浏览器为图像发送 GET 时才会发送图像文件。这将成为多部分请求。

Or you can do it like this. It is possible to send your image in binary form in HTML. Use :

或者你可以这样做。可以在 HTML 中以二进制形式发送图像。用 :

<img src="data:image/gif;base64,imagedata">

where imagedata is a base64 encoding of gif image. So do this in node.js :

其中 imagedata 是 gif 图像的 base64 编码。所以在 node.js 中这样做:

//Write text in response.
content = get-image-file-contents;     //store image into content
imagedata = new Buffer(content).toString('base64');    //encode to base64
response.write('<img src="data:image/gif;base64,'+imagedata+'">');//send image
response.end();

Check here for correct image conversion NodeJS base64 image encoding/decoding not quite working

在这里检查正确的图像转换NodeJS base64 图像编码/解码不太工作

This sends one response which sends both text and image. Only one header is required for response response.writeHead(200, {'content-type':'text/html'});

这会发送一个同时发送文本和图像的响应。响应只需要一个标头response.writeHead(200, {'content-type':'text/html'});

回答by wheresrhys

You can only write one value to a given header, so the second header is overwriting the first. Two solutions are

您只能将一个值写入给定的标头,因此第二个标头将覆盖第一个标头。两种解决方案是

  1. write out a url to the image in the html - will be slightly slower for the user (needing an extra http request to fetch the image), but depending on the use case this is normally acceptable and very simple to implement
  2. convert the image to a data-uri string and include this in the html as the source of the image. More complicated to implement than the first approach ( I don't know of any libraries for doing the conversion in node) and with negligible benefits.
  1. 在 html 中写出图像的 url - 对用户来说会稍微慢一些(需要额外的 http 请求来获取图像),但根据用例,这通常是可以接受的,并且实现起来非常简单
  2. 将图像转换为 data-uri 字符串,并将其作为图像源包含在 html 中。实施起来比第一种方法更复杂(我不知道有任何用于在 node 中进行转换的库)并且好处可以忽略不计。