Can I use require(“path”).join to safely concatenate urls?

前端 未结 15 460
臣服心动
臣服心动 2020-12-23 13:06

Is this safe to use require(\"path\").join to concatenate URLs, for example:

require(\"path\").join(\"http://example.com\", \"ok\"); 
//returns          


        
15条回答
  •  礼貌的吻别
    2020-12-23 13:46

    No, you should not use path.join() to join URL elements.

    There's a package for doing that now. So rather than reinvent the wheel, write all your own tests, find bugs, fix them, write more tests, find an edge case where it doesn't work, etc., you could use this package.

    url-join

    https://github.com/jfromaniello/url-join

    Install

    npm install url-join

    Usage

    var urljoin = require('url-join');
    
    var fullUrl = urljoin('http://www.google.com', 'a', '/b/cd', '?foo=123');
    
    console.log(fullUrl);
    

    Prints:

    'http://www.google.com/a/b/cd?foo=123'

提交回复
热议问题