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

前端 未结 15 526
臣服心动
臣服心动 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:45

    If you use Angular, you can use Location:

    import { Location } from '@angular/common';
    // ...
    Location.joinWithSlash('beginning', 'end');
    

    Works only on 2 arguments though, so you have to chain calls or write a helper function to do that if needed.

    0 讨论(0)
  • 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'

    0 讨论(0)
  • 2020-12-23 13:46

    When I tried PATH for concatenating url parts I run into problems. PATH.join stripes '//' down to '/' and this way invalidates an absolute url (eg. http://... -> http:/...). For me a quick fix was:

    baseurl.replace(/\/$/,"") + '/' + path.replace(/^\//,"") )
    

    or with the solution posted by Colonel Panic:

    [pathA.replace(/^\/|\/$/g,""),pathB.replace(/^\/|\/$/g,"")].join("/")
    
    0 讨论(0)
提交回复
热议问题