Подтвердить что ты не робот

Node.js проверить, существует ли удаленный URL-адрес

Как проверить, существует ли URL-адрес, не вытаскивая его? Я использую следующий код, но он загружает весь файл. Мне просто нужно проверить, что он существует.

app.get('/api/v1/urlCheck/', function (req,res) {
    var url=req.query['url'];
    var request = require('request');
    request.get(url, {timeout: 30000, json:false}, function (error, result) {
        res.send(result.body);

    });

});

Цените любую помощь!

4b9b3361

Ответ 1

Попробуйте следующее:

var http = require('http'),
    options = {method: 'HEAD', host: 'stackoverflow.com', port: 80, path: '/'},
    req = http.request(options, function(r) {
        console.log(JSON.stringify(r.headers));
    });
req.end();

Ответ 2

Спасибо! Вот он, инкапсулированный в функцию (обновленный 5/30/17 с требованием снаружи):

    var http = require('http'),
         url = require('url');

    exports.checkUrlExists = function (Url, callback) {
        var options = {
            method: 'HEAD',
            host: url.parse(Url).host,
            port: 80,
            path: url.parse(Url).pathname
        };
        var req = http.request(options, function (r) {
            callback( r.statusCode== 200);});
        req.end();
    }

Это очень быстро (я получаю около 50 мс, но это будет зависеть от вашего соединения и скорости сервера). Обратите внимание, что он также довольно простой, т.е. Он не будет обрабатывать переадресации очень хорошо...

Ответ 3

Просто используйте url-exists пакет npm для проверки, существует ли URL-адрес или нет

var urlExists = require('url-exists');

urlExists('https://www.google.com', function(err, exists) {
  console.log(exists); // true 
});

urlExists('https://www.fakeurl.notreal', function(err, exists) {
  console.log(exists); // false 
});

Ответ 4

require в функции неправильно в узле. Придерживающийся метод ES6 поддерживает все правильные http-статусы и, конечно, возвращает ошибку, если у вас плохой хост, такой как fff.kkk

checkUrlExists(host,cb) {
    http.request({method:'HEAD',host,port:80,path: '/'}, (r) => {
        cb(null, r.statusCode >= 200 && r.statusCode < 400 );
    }).on('error', cb).end();
}

Ответ 5

Используя другие ответы в качестве ссылки, здесь обещанная версия, которая также работает с https uris (для узла 6+):

const http = require('http');
const https = require('https');
const url = require('url');

const request = (opts = {}, cb) => {
  const requester = opts.protocol === 'https:' ? https : http;
  return requester.request(opts, cb);
};

module.exports = target => new Promise((resolve, reject) => {
  let uri;

  try {
    uri = url.parse(target);
  } catch (err) {
    reject(new Error('Invalid url ${target}'));
  }

  const options = {
    method: 'HEAD',
    host: uri.host,
    protocol: uri.protocol,
    port: uri.port,
    path: uri.path,
    timeout: 5 * 1000,
  };

  const req = request(options, (res) => {
    const { statusCode } = res;

    if (statusCode >= 200 && statusCode < 300) {
      resolve(target);
    } else {
      reject(new Error('Url ${target} not found.'));
    }
  });

  req.on('error', reject);

  req.end();
});

Это можно использовать так:

const urlExists = require('./url-exists')

urlExists('https://www.google.com')
  .then(() => {
    console.log('Google exists!');
  })
  .catch(() => {
    console.error('Invalid url :(');
  });

Ответ 6

Взгляните на пакет npm, существующий по URL- адресу https://www.npmjs.com/package/url-exists

Настройка:

$ npm install url-exists

Useage:

const urlExists = require('url-exists');

urlExists('https://www.google.com', function(err, exists) {
  console.log(exists); // true 
});

urlExists('https://www.fakeurl.notreal', function(err, exists) {
  console.log(exists); // false 
});

Вы также можете обещать это, чтобы воспользоваться преимуществами await и async:

const util = require('util');
const urlExists = util.promisify(require('url-exists'));

let isExists = await urlExists('https://www.google.com'); // true
isExists = await urlExists('https://www.fakeurl.notreal'); // false

Удачного кодирования!

Ответ 7

мое ожидаемое решение async ES6, выполняющее запрос HEAD:

// options for the http request
let options = {
    host: 'google.de',
    //port: 80,  optional
    //path: '/'  optional
}

const http = require('http');

// creating a promise (all promises a can be awaited)
let isOk = await new Promise(resolve => {
    // trigger the request ('HEAD' or 'GET' - you should check if you get the expected result for a HEAD request first (curl))
    // then trigger the callback
    http.request({method:'HEAD', host:options.host, port:options.port, path: options.path}, result =>
        resolve(result.statusCode >= 200 && result.statusCode < 400)
    ).on('error', resolve).end();
});

// check if the result was NOT ok
if (!isOk) 
    console.error('could not get: ' + options.host);
else
    console.info('url exists: ' + options.host);

Ответ 8

Если у вас есть доступ к пакету request, вы можете попробовать это:

const request = require("request")
const urlExists = url => new Promise((resolve, reject) => request.head(url).on("response", res => resolve(res.statusCode.toString()[0] === "2")))
urlExists("https://google.com").then(exists => console.log(exists)) // true