如何在nodejs urlparsing中包含端口
那么…我有一个非常简单的用例。
我有两个string:
var a = 'localhost:3000', b = '/whatever/; // this can also be whatever/ or /whatever
我需要parsing
url.parse(a, b); // so that it takes care of dealing with slashes
但是我明白了
localhost:/whatever/ instead of localhost:3000/whatever/
任何指针?
谢谢!
如果你比较下面两个调用,你会发现在string的前面添加一个协议会产生很大的变化:
> 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/' } >
一个选项可以做一个规范化的path :
path.normalize('/foo/bar//baz/asdf'); // the path here // returns '/foo/bar/baz/asdf'
然后:
var cleanUrl = 'localhost:3000' + path.normalize(yourpath);