所谓图片防盗链,就是为了防止其他域名下的网页使用原网页的图片,它们是通过判断referer和host两个请求体字段来判断的,例如在这个pic1.me网站下显示的是原本的图片,到了pic2.me就是另一张图片,而且他们图片路径是一样的。下面就通过代码来实现一下
//app.js
const koa=require('koa')
const Router=require('koa-router')
const app=new koa();
const router=new Router();
const fs=require('fs');
const path=require('path')
var data=fs.readFileSync('./index.html','utf-8')
router.get('/index',async ctx=>{ctx.body=data})
router.get('/public/img1',async ctx=>{console.log(ctx.request.host)
var s=ctx.request.header.referer.split('http://')[1]
if(s.includes(ctx.request.host)){
var data=null;
data=fs.createReadStream(path.join(__dirname,'public','./1.jpg'));
}else{
var data=null;
data=fs.createReadStream(path.join(__dirname,'public','./5.jpg'));
}
ctx.body=data
})
app.use(router.routes())
app.use(router.allowedMethods());
app.listen(4050,()=>{console.log('监听4050端口')});
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<img src="http://www.pic1.me:4050/public/img1">
</body>
</html>
然后在host文件下设置两个对应的ip地址即可
这样就完成了