请问nodejs可以不可以检测一个图片地址是否禁止外链?
发布于 8 年前 作者 kilik52 5110 次浏览 来自 问答

比如https://pic2.zhimg.com/ec713dcf516cd4149a5ebb93bdebbd15_b.png 图片是禁止外链的。 我能否用程序的方式来知道这张图片禁止外链?

5 回复

应该是不可以

参考

var parse = require('url').parse;
var request = {
  'http:': require('http').request,
  'https:': require('https').request
};
function isImgAvailable(path, referer, cb) {
  var info = parse(path);
  var headers = {
    'Connection': 'keep-alive',
    'Cache-Control': 'max-age=0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Upgrade-Insecure-Requests': '1',
    'Referer': referer || '',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/45.0.2454.101 Chrome/45.0.2454.101 Safari/537.36',
    'Accept-Encoding': 'gzip, deflate, sdch',
    'Accept-Language': 'en-US,en;q=0.8'
  };
  var req = request[info.protocol]({
    hostname: info.hostname,
    path: info.path,
    method: 'head',
    headers: headers
  }, function (res) {
    if (res.statusCode.toString().indexOf('2') !== 0) {
      cb(null, false);
    } else {
      cb(null, true);
    }
  });
  req.end();
  req.on('error', function(err) {
    // ? 
    cb(null, false);
  });
}

function isAvaiableInCNode(path, cb) {
  isImgAvailable(path, 'https://condejs.org', cb);
}

isAvaiableInCNode('https://pic2.zhimg.com/ec713dcf516cd4149a5ebb93bdebbd15_b.png', function (err, result) {
  console.log(result);
});
isAvaiableInCNode('https://dn-cnodestatic.qbox.me/public/images/cnodejs_light.svg', function (err, result) {
  console.log(result);
});
isAvaiableInCNode('https://not.exists.test', function (err, result) {
  console.log(result);
});

@William17 懂了,就是设一个referer。非常感谢!

检查下 Referer就行了

回到顶部