简体   繁体   中英

Send Image from subdomain Express.js

Lets say I have this for local testing.

sendImage: async function(req, res) {

    console.log(req.hostname);

    var filepath = path.join(__dirname, '../../img/uploads/' + req.params.year + '/' + req.params.month + '/' + req.params.id);
    //console.log(filepath);
    res.sendFile(filepath);
}

This gets a file based on a path to the file of course. Now lets say that the img folder is actually the folder to the subdomain, and I wanted to send the image from the subdomain itself, so instead of the api requesting to the main site aka mysite.com, it would request from img.mysite.com. I have this set up in such a way that it goes from img={'/api/date/img}

Basically I need the image requests to go from mysite.com/api/date/img to img.mysite.com/date/img

Is there a way to do this with express directly?

By the time you are in the middle of this code, the browser has already requested the image from the Express server. It's too late to stop it from requesting this URL.

So your options:

  • Have the express server give the browser the image it requested (which is what you are doing now)
  • Issue a redirect response to tell the browser that the image isn't at the URL and it should go to a different URL (on the subdomain)
  • Take a step back and change the code which told the browser to ask for this URL so it outputs the URL on the subdomain instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM