koa实现图片防盗链

所谓图片防盗链,就是为了防止其他域名下的网页使用原网页的图片,它们是通过判断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地址即可

这样就完成了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值