【问题标题】:how to include port in nodejs url parse如何在nodejs url解析中包含端口
【发布时间】:2014-05-07 04:15:21
【问题描述】:

嗯...我有一个非常简单的用例。

我有两个字符串:

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/

任何指针?

谢谢!

【问题讨论】:

  • url.parse 只接受一个字符串参数。

标签: javascript node.js http url


【解决方案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/' }
>

【讨论】:

    【解决方案2】:

    一个选项可以做一个normalize path

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

    然后:

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

    【讨论】:

      猜你喜欢
      • 2013-04-16
      • 1970-01-01
      • 2011-05-18
      • 2014-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-22
      相关资源
      最近更新 更多