2014-03-27 37 views
1

那麼......我有一個非常簡單的用例。如何在nodejs中包含端口url解析

我有兩個字符串:

var a = 'localhost:3000', 
    b = '/whatever/; // this can also be whatever/ or /whatever 

我需要解析

url.parse(a, b); // so that it takes care of dealing with slashes 

,但我得到

localhost:/whatever/ instead of localhost:3000/whatever/ 

任何指針?

謝謝!

+0

'url.parse'只需要一個字符串參數。 –

回答

1

如果你比較以下兩個電話,你會看到加入議定書字符串前造成很大的差異:

> url.parse('http://localhost:3000', '/whatever/') 
{ protocol: 'http:', 
    slashes: true, 
    auth: null, 
    host: 'localhost:3000', 
    port: '3000', 
    hostname: 'localhost', 
    hash: null, 
    search: '', 
    query: {}, 
    pathname: '/', 
    path: '/', 
    href: 'http://localhost:3000/' } 
> 

沒有

> url.parse('localhost:3000', '/whatever/') 
{ protocol: 'localhost:', 
    slashes: null, 
    auth: null, 
    host: '3000', 
    port: null, 
    hostname: '3000', 
    hash: null, 
    search: '', 
    query: {}, 
    pathname: null, 
    path: null, 
    href: 'localhost:3000' } 
> 

什麼你可能尋找添加協議,然後使用+而不是,

> url.parse('http://localhost:3000' + '/whatever/') 
{ protocol: 'http:', 
    slashes: true, 
    auth: null, 
    host: 'localhost:3000', 
    port: '3000', 
    hostname: 'localhost', 
    hash: null, 
    search: null, 
    query: null, 
    pathname: '/whatever/', 
    path: '/whatever/', 
    href: 'http://localhost:3000/whatever/' } 
> 
+0

這就是我的朋友 – jmingov

0

一個選項CA做一個normalize path有:

path.normalize('/foo/bar//baz/asdf'); // the path here 

// returns '/foo/bar/baz/asdf' 

則:

var cleanUrl = 'localhost:3000' + path.normalize(yourpath);