Bird
0
0

How can you safely handle URLs with missing protocols when parsing in Node.js using the WHATWG URL API?

hard📝 Application Q9 of 15
Node.js - URL and Query String Handling
How can you safely handle URLs with missing protocols when parsing in Node.js using the WHATWG URL API?
AReplace missing protocol with 'ftp://' before parsing.
BUse url.parse() which handles missing protocols automatically.
CCall new URL() directly; it accepts URLs without protocols.
DPrepend 'http://' to the URL string before parsing if no protocol is present.
Step-by-Step Solution
Solution:
  1. Step 1: Understand WHATWG URL requirements

    new URL() requires a full URL including protocol; missing protocol causes error.
  2. Step 2: Fix missing protocol

    Prepending 'http://' ensures the URL is valid for parsing.
  3. Final Answer:

    Prepend 'http://' to the URL string before parsing if no protocol is present. -> Option D
  4. Quick Check:

    Add protocol before new URL() to avoid errors [OK]
Quick Trick: Add 'http://' if URL lacks protocol before parsing [OK]
Common Mistakes:
  • Assuming new URL() accepts protocol-less URLs
  • Using url.parse() expecting automatic fix
  • Replacing protocol with wrong scheme

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes