How to send a file from remote URL as a GET response in Node.js Express app?

前端 未结 1 1614
北恋
北恋 2020-12-14 01:57

Context: Multi-tier Node.js app with Express. Front end hosted as Azure website, back end data is coming from Parse.

I have a GET endpoint and I want the user exper

相关标签:
1条回答
  • 2020-12-14 02:20

    You can use the http.request() function to make a request to your externalURL and then pipe() the response back to res. Using pipe() will stream the file through your server to the browser, but it won't save it to disk at any point. If you want the file to be downloaded as well (as opposed to just being displayed in the browser), you'll have to set the content-disposition header.

    Here's an example of a server which will "download" the google logo. This is just using the standard http module and not express, but it should work basically the same way:

    var http = require('http');
    
    http.createServer(function(req, res) {
        var externalReq = http.request({
            hostname: "www.google.com",
            path: "/images/srpr/logo11w.png"
        }, function(externalRes) {
            res.setHeader("content-disposition", "attachment; filename=logo.png");
            externalRes.pipe(res);
        });
        externalReq.end();
    }).listen(8080);
    

    If you want to use the request module, it's even easier:

    var http = require('http'),
        request = require('request');
    
    http.createServer(function(req, res) {
        res.setHeader("content-disposition", "attachment; filename=logo.png");
        request('http://google.com/images/srpr/logo11w.png').pipe(res);
    }).listen(8080);
    

    Note: The name of the file that the browser will save is set by the filename= part of the content-disposition header; in this case I set it to logo.png.

    0 讨论(0)
提交回复
热议问题