So I want to load an image from an external URL.
var https = require('node:https');
export const loadImageFromUrl = (url: string) => {
return new Promise((resolve, reject) => {
try {
https.request(url, function (response: any) {
resolve(response);
});
} catch (err) {
reject(err);
}
});
};
For example, the image is from https://en.pimg.jp/054/313/779/1/54313779.jpg
. When I run the code, it gives me this error:
Error: connect ECONNREFUSED 127.0.0.1:443
This is weird, the URL is not from my local computer, why does https
search from my local address?
CodePudding user response:
You can try this code. It should work.
You can have a look at the live demo here
const https = require("https");
const { URL } = require("url");
const loadImageFromUrl = (url) => {
const urlParams = new URL(url);
const hostname = urlParams.hostname;
const path = urlParams.pathname;
const options = {
hostname: hostname,
port: 443,
path: path,
method: "GET",
};
const request = https.request(options, (res) => {
res.on("data", (data) => {
console.log(`response data: ${data}`);
});
});
request.on("error", (error) => {
console.error(`Error on Get Request --> ${error}`);
});
request.end();
};
loadImageFromUrl("https://en.pimg.jp/054/313/779/1/54313779.jpg");