如何使用Node.js将HTTP请求中的图像显示到外部API

我有一种情况,为了获取我正在构build的网站的图像,我需要向外部服务器发送http请求以获取信息。 目前,来自请求的响应有两种forms,XML和图像。 我正在使用Node.js.

对于XML,我可以毫无问题地parsing它,并且可以将它传递给一个variables并像其他所有处理一样。 随着图像,我卡住了,我不知道如何让他们“显示”在他们的请求后,在网页上。 我所能得到的最远的地方是在邮递员中正确设置请求。 我的问题是,我可以从正在向另一个服务器发出的请求的响应主体中提取图像,并将其显示在我正在构build的Web应用程序中?

我对后端世界非常陌生,我正在努力学习。 这是我能够find并用于parsing从API获得的XML响应的一个例子

var request = require("request"); var express = require("express"); var jsxml = require("node-jsxml"); var app = express(); var fs = require("fs"); app.get('/users', function(req,res) { console.log("List of users requested."); // We will grab the list of users from the specified site, but first we have to grab the site id // (Same idea as when we added users. We could have checked if req.session.SiteID has been populated, // but I chose to keep it simple instead) request( { url: 'http://' + SERVERURL + '/api/2.0/sites/' + SITE + '?key=name', headers: { 'Content-Type': 'text/xml', 'X-Tableau-Auth': req.session.authToken } }, function(err, response, body) { if(err) { req.session.err = err; res.redirect('/'); } else { var bodyXML = new jsxml.XML(body); console.log("site id: " + siteID); } // OK. We have the site, now let's grab the list of users // Since we're just making a GET request, we don't need to build the xml. All the is needed // is the SiteID which is inserted in the url and the auth token which is included in the headers request( { url: 'http://' + SERVERURL + '/api/2.0/sites/' + siteID + '/users/', headers: { 'Content-Type': 'text/xml', 'X-Tableau-Auth': authToken } }, function(err, response, body) { if(err) { req.session.err = err; } else { // A succesful request returns xml with a <users> which contains multiple <user> elements. // The <user> elements have name attributes and id attributes which we'll grab, store in a // javascript object and render those in the html that loads. var bodyXML = new jsxml.XML(body); bodyXML.descendants('user').each(function(item, index) { userIDs[item.attribute('name').getValue()] = item.attribute('id').getValue(); }); for(var user in userIDs) { console.log(user + " " + userIDs[user]); } } res.render("users.ejs", { err: req.session.err, userIDs: userIDs, site: SITE }); } ); } ); }); 

任何帮助将非常感激。 谢谢!

第1步:获取图像并将其保存在节点服务器上。 请求关于stream的模块文档以获取更多选项

 request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png')); 

步骤2:发送保存的图像作为响应。

 app.get('/display', function(req, res)) { fs.readFile('doodle.png', function(err, data) { if (err) throw err; // Fail if the file can't be read. else { res.writeHead(200, {'Content-Type': 'image/jpeg'}); res.end(data); // Send the file data to the browser. } }); };