LoginSignup
2
1

More than 3 years have passed since last update.

Node.js + JavaScript で HTTP リダイレクト先の URL を取得する

Posted at

概要

  • Node.js + JavaScript で HTTP リダイレクト先の URL を取得する
  • 動作確認環境: Node.js 14.7.0 + macOS Catalina

ソースコード

get_redirect.js というファイル名で以下の内容を保存する。

get_redirect.js
'use strict'

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

// リダイレクト先 URL を取得する関数
function get_redirect_url(src_url) {
  return new Promise((resolve, reject) => {
    try {
      // https と http で使うモジュールを変える
      const client = src_url.startsWith('https') ? https : http
      // 4xx や 5xx ではエラーが発生しないので注意
      client.get(src_url, (res) => {
        // HTTP レスポンスから Location ヘッダを取得 (ヘッダ名は小文字)
        resolve(res.headers['location'])
      }).on('error', (err) => {
        reject(err)
      })
    } catch(err) {
      reject(err)
    }
  })
}

(async () => {

  // コマンドライン引数を取得
  const src_url = process.argv[2]

  // リダイレクト先URLを取得
  const redirect_url = await get_redirect_url(src_url)
    .catch(err => {
      console.log(err)
    })

  // リダイレクト先URLを出力
  if (redirect_url) {
    console.log(redirect_url)
  }
})()

実行例。

$ node get_redirect.js https://bit.ly/3kmTOkc
https://t.co/yITSBp4ino
$ node get_redirect.js https://t.co/yITSBp4ino
https://qiita.com/niwasawa
$ node get_redirect.js https://qiita.com/niwasawa

参考資料

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1