如何使用 Node.js 显示从 http 请求到外部 API 的图像 [英] How to display image from http request to external API with Node.js

查看:30
本文介绍了如何使用 Node.js 显示从 http 请求到外部 API 的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,为了获取我正在构建的站点的图像,我需要向外部服务器发出 http 请求以获取信息.目前,请求的响应有两种形式,XML 和图像.我正在使用 Node.js.

I have a situation where in order to get images for a site that I am building, I need to make a http request to an external server for information. Currently, the responses from the requests come in two forms, XML and images. I am doing this using Node.js.

对于 XML,我可以毫无问题地解析它,并且可以将其传递给变量并像其他所有内容一样进行处理.对于图像,我被卡住了,我不知道如何在提出请求后让它们显示"在页面上.我能得到的最远的是在邮递员中正确设置请求.我的问题是,我可以从我向另一台服务器发出的请求的响应正文中提取图像,并让它显示在我正在构建的 Web 应用程序中吗?

For the XML, I'm able to parse it without issues and it can be passed into a variable and handled like everything else. With the images, I'm stuck, I have no idea how to get them "displayed" on the page after making the request for them. The farthest I have been able to get is to correctly set the request up in postman. My question is, can I pull the image from the body of the response of the request that I'm making to another server and get it to display in the web app that I'm building?

我对后端世界很陌生,我正在努力学习.这是我能够找到并用于解析从 API 获得的 XML 响应的示例

I'm very new to the back end world and am trying to learn as I go. This is an example of what I have been able to do find and use for parsing an XML response that I get from the API

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
                });
            }
        );
    }
);
});

任何帮助将不胜感激.谢谢!

Any help would be hugely appreciated. Thanks!

推荐答案

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

Step 1: Fetch image and save it on node server. request module documentation on streaming for more options

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

第 2 步:发送保存的图像作为响应.

Step 2: send the saved image as response.

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.
    }
  });
};

这篇关于如何使用 Node.js 显示从 http 请求到外部 API 的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆