Node.js 服务端如何实现图片防盗链 All In One
- 无扩图片展名 URL
- blob URL
- 设置有效期 链接
- 禁用缓存
- referrer CORS
demos
http://127.0.0.1:5500/image.html
blob:http://127.0.0.1:5500/a9eecfe3-6a40-46d3-a1d3-d5f848af38e6
{
"url": "https://cdn.xgqfrms.xyz/logo/icon.png"
}
http://localhost:3000/image
server.js
// const app = express();
// app.get('/image', async (req, res) => {
// const url = 'https://example.com/images/test.jpg';
// res.send(/**/); // How do I send the image binary data from the url?
// });
// const request = require('request');
// const axios = require('axios');
// const fetch = require('node-fetch');
const express = require('express');
const app = express();
app.use(function (req, res, next) {
// JSON parse
// console.log('req.body', req.body);
// fix CORS bug ✅
res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
// res.header("Content-Security-Policy", "connect-src *");
// res.header("Content-Security-Policy", "connect-src '*'");
// res.header("Content-Security-Policy", "connect-src 'localhost'");
// res.header("Content-Security-Policy", "connect-src localhost");
// Content-Security-Policy: connect-src <source>;
// Content-Security-Policy: connect-src <source> <source>;
// res.header('Content-Type', 'application/json');
// res.setHeader('Content-Type', 'application/json');
next();
});
// header("Access-Control-Allow-Origin: *");
app.get('/image', async (req, res) => {
const url = `https://cdn.xgqfrms.xyz/logo/icon.png`;
// res.write(url)
// res.send()
// res.send(url)
const json = {
url,
}
// ✅ 返回 JSON string
// res.header('Content-Type', 'application/json');
// res.json(JSON.stringify(json))
// 🚀 返回 JSON object
res.json(json)
// res.set('Content-Type', 'text/html');
// res.send(JSON.stringify(url));
// res.sendFile(url)
});
// app.get('/image', async (req, res) => {
// // const url = 'https://example.com/images/test.jpg';
// const url = `https://cdn.xgqfrms.xyz/logo/icon.png`;
// request({
// url: url,
// encoding: null
// },
// (err, resp, buffer) => {
// if (!err && resp.statusCode === 200){
// res.set("Content-Type", "image/jpeg");
// res.send(resp.body);
// }
// });
// });
const defaultPort = 3000;
const port = process.env.PORT || defaultPort
app.listen(port, () => {
console.log(`app is running on http://localhost:${port}`)
});
// https://cdn.xgqfrms.xyz/logo/icon.png
// http://localhost:3000/image
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="author" content="xgqfrms">
<meta name="generator" content="VS code">
<title>image</title>
</head>
<body>
<header>
<h1>image</h1>
</header>
<main>
<img id="img" data-src="http://localhost:3000/image" src="" alt="" />
</main>
<footer>
<p>copyright© xgqfrms 2022</p>
</footer>
<script>
function generatorBlobVideo(url, dom) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'arraybuffer';
xhr.onload = function(res) {
let blob = new Blob(
[xhr.response],
{'type' : 'image/png'},
);
console.log(`blob =`, blob)
let urlBlob = URL.createObjectURL(blob);
console.log(`urlBlob =`, urlBlob)
dom.src = urlBlob;
};
xhr.send();
}
window.onload = () => {
async function test() {
const dom = document.querySelector('#img');
const url = `${dom.dataset.src}`;
const res = await fetch(url, {
// method: 'GET', // *GET, POST, PUT, DELETE, etc.
// mode: 'cors', // no-cors, *cors, same-origin
// cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
// credentials: 'same-origin',
// credentials: 'include',
// method: 'GET',
// // mode: 'no-cors',
// mode: 'cors',
// headers: {
// // 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;',
// // 'Content-Type': 'text/html',
// 'Accept': 'application/json',
// // 'Content-Type': 'application/json',
// "Access-Control-Allow-Origin": "*",
// },
}).then(res => res.json())
// }).then(res => {
// console.log(`res =`, res)
// // console.log(`text =`, res.text())
// // return res.text()
// console.log(`text =`, res.json())
// return res.json()
// })
console.log(`res`, res, typeof res)
generatorBlobVideo(res.url, dom);
};
test()
// setTimeout(() => {
// test()
// }, 3000);
}
</script>
</body>
</html>
blob
refs
https://stackoverflow.com/questions/60754335/how-do-i-send-image-data-from-a-url-using-express
©xgqfrms 2012-2021
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
未经授权禁止转载,违者必究!