Hướng dẫn get current url nodejs

In 2021

The above answers are working fine but not preferred by the Documentation because url.parse is now legacy so I suggest you to use new URL() function if you want to get more control on url.

Express Way

You can get Full URL from the below code.

`${req.protocol}://${req.get('host')}${req.originalUrl}`

Example URL: http://localhost:5000/a/b/c?d=true&e=true#f=false

Fixed Properties ( you will get the same results in all routes )

req.protocol: http
req.hostname: localhost
req.get('Host'): localhost:5000
req.originalUrl: /a/b/c?d=true&e=true
req.query: { d: 'true', e: 'true' }

Not Fixed Properties ( will change in every route because it controlled by express itself )

Route: /

req.baseUrl: <blank>
req.url: /a/b/c?d=true&e=true
req.path: /a/b/c

Route /a

req.baseUrl: /a
req.url: /b/c?d=true&e=true
req.path: /b/c

Documentation: http://expressjs.com/en/api.html#req.baseUrl

URL Package Way

In the URL function, you will get the same results in every route so properties are always fixed.

Properties

Hướng dẫn get current url nodejs

const url = new URL(`${req.protocol}://${req.get('host')}${req.originalUrl}`);
console.log(url)

You will get the results like the below. I changed the order of the properties as per the image so it can match the image flow.

URL {
  href: 'http://localhost:5000/a/b/c?d=true&e=true',
  protocol: 'http:',
  username: '',
  password: '',
  hostname: 'localhost',
  port: '5000',
  host: 'localhost:5000',
  origin: 'http://localhost:5000',
  pathname: '/a/b/c',
  search: '?d=true&e=true',
  searchParams: URLSearchParams { 'd' => 'true', 'e' => 'true' },
  hash: ''
}

Note: Hash can not send to the server because it treats as Fragment in the server but you will get that in the client-side means browser.

Documentation: https://nodejs.org/api/url.html#url_new_url_input_base

Nội dung bài viết

Video học lập trình mỗi ngày

Metadata là gì? Phân tích url từ nodejs chúng ta có thể lấy Title, Description, Keywords và Images từ một url. Một tips nodejs đơn giản nhưng hiệu quả dành cho dev mới. Giờ đây khi sử dụng node thì có rất nhiều module hỗ trợ từ npm, cho nên rất dễ dàng.

Hay meta keywords là gì? Nó còn gọi là siêu dữ liệu (data about data). Nói cách khác, đó là thông tin được sử dụng để mô tả dữ liệu chứa trong một cái gì đó như trang web, tài liệu hoặc tệp. 

Một cách khác để nghĩ về metadata đó chính là chi tiết về một object nào đó, ví dụ: Trong file thì sẽ chứa những thông tin như size, created, author, keywords khai báo. Ở ví dụ khác, thì về âm nhạc, metadata đó chính là tên bài hát, một album, và thời gian phát hành. Nôm na là vậy... Còn ở website thì metadata chính là những tag meta trên head, bao gồm như title, description, name,img... Nên trong bài viết này giới thiệu cho các bạn cách lấy metadata trong nodejs như thế nào? 

Trường hợp nào cần lấy metadata, haha, thì tuỳ vào nhiều trường hợp của dự án, tính chất khác nhau. Chẳng hạn trong chat skype, messenger, thì khi gửi một url, thì hiển thị nội dung trong khung chat như hình ảnh dưới đây. 

Còn trong những blog lập trình thì có thể get metadata để lưu lại rss để lưu lại học tập như extension rss javascript như hình ảnh tiếp theo.

Get Metadata from url with nodejs

tipjs sẽ hướng dẫn hai cách khi sử dụng module với npm # Sử dụng url-metadata install package url-metadata

AnonyStick$ npm i url-metadata --save

User in file index.js

const urlMetadata = require('url-metadata');

//get metadata với https://fb.com

urlMetadata('https://fb.com').then( async(metadata) => { 

    console.log(JSON.stringify(metadata, '*****', 8));

})

Ouput:

{
        "url": "https://www.facebook.com/",
        "canonical": "https://www.facebook.com/",
        "title": "Facebook - Đăng nhập hoặc đăng ký",
        "image": "https://www.facebook.com/images/fb_icon_325x325.png",
        "author": "",
        "description": "Tạo một tài khoản để đăng nhập Facebook. Kết nối với bạn bè, 
        gia đình và những người mà bạn biết. Chia sẻ ảnh và video, gửi tin nhắn và nhận cập nhật.",
        "keywords": "",
        "source": "www.facebook.com",
        "og:url": "https://www.facebook.com/",
        "og:locale": "vi_VN",
        "og:locale:alternate": "",
        "og:title": "",
        "og:type": "",
        "og:description": "",
        "og:determiner": "",
        "og:site_name": "Facebook",
        "og:image": "https://www.facebook.com/images/fb_icon_325x325.png",
        "og:image:secure_url": "",
        "og:image:type": "",
        "og:image:width": "",
        "og:image:height": "",
        "price": "",
        "priceCurrency": "",
        "availability": ""
}

Cách thứ hai 

# sử dụng html-metadata-parser 

install package html-metadata-parser

AnonyStick$ npm i html-metadata-parser --save

User in file index.js

const Meta = require('html-metadata-parser');

(async () => {

    var result = await Meta.parser('https://fb.com');

     console.log(JSON.stringify(result, null, 3));


})();


Ouput:
{
   "meta": {
      "title": "Facebook - Đăng nhập hoặc đăng ký",
      "description": "Tạo một tài khoản để đăng nhập Facebook. Kết nối với bạn bè, 
      gia đình và những người mà bạn biết. Chia sẻ ảnh và video, gửi tin nhắn và nhận cập nhật."
   },
   "og": {
      "images": [
         {
            "url": "https://www.facebook.com/images/fb_icon_325x325.png"
         }
      ],
      "videos": [],
      "site_name": "Facebook",
      "url": "https://www.facebook.com/",
      "image": "https://www.facebook.com/images/fb_icon_325x325.png"
   },
   "images": [
      {
         "url": "https://static.xx.fbcdn.net/rsrc.php/v3/yi/r/OBaVg52wtTZ.png",
         "width": 537,
         "height": 195
      },
      {
         "url": "https://static.xx.fbcdn.net/rsrc.php/v3/yb/r/GsNJNwuI-UM.gif",
         "width": 16,
         "height": 11
      },
      {
         "url": "https://static.xx.fbcdn.net/rsrc.php/v3/yb/r/GsNJNwuI-UM.gif",
         "width": 16,
         "height": 11
      },
      {
         "url": "https://facebook.com/security/hsts-pixel.gif?c=3.2.5",
         "width": 0,
         "height": 0
      }
   ]
}

Notes: Khi bạn sử dụng html-metadata-parser thì có hai lựa chọn trên kia là sử dụng async/await để get metadata. Còn bạn nào muốn sử dụng callbacks thì có thể xem code dưới đây.

var Meta = require('html-metadata-parser');

Meta.parser('https://fb.com', function (err, result) {

    console.log(result);
})

Xong! Chỉ đơn giản vậy thôi, giờ thì thử apply code xem chạy như thế nào đi. Chúc một ngày vui vẻ.