文档里的几个参数的解释,不明白,求解释。能举几个例子么?
发布于 11 年前 作者 ggaaooppeenngg 4066 次浏览 最后一次编辑是 8 年前

url.parse(urlStr, [parseQueryString], [slashesDenoteHost])# Take a URL string, and return an object.

Pass true as the second argument to also parse the query string using the querystring module. Defaults to false.

Pass true as the third argument to treat //foo/bar as { host: ‘foo’, pathname: ‘/bar’ } rather than { pathname: ‘//foo/bar’ }. Defaults to false.

6 回复

Pass true as the second argument to also parse the query string using the querystring module. Defaults to false.

第二个参数是 true 时, 就使用 querystring 模块 parse query( ?a=b -> {a:b}) 部分.

同学以后最到这样的问题的时候自己先动手 2,第二个参数如果是true,表示会用 querystring 这个模块来解析查询字符串 3.第三个参数表是是否//后面的作为host,并且以host为key加入到返回值中

跑了个例子:

➤➤ coffee
coffee> url = require 'url'
{ parse: [Function: urlParse],
  resolve: [Function: urlResolve],
  resolveObject: [Function: urlResolveObject],
  format: [Function: urlFormat],
  Url: [Function: Url] }
coffee> url.parse '/a?a=3&b=4', no
{ protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: '?a=3&b=4',
  query: 'a=3&b=4',
  pathname: '/a',
  path: '/a?a=3&b=4',
  href: '/a?a=3&b=4' }
coffee> url.parse '/a?a=3&b=4', yes
{ protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: '?a=3&b=4',
  query: { a: '3', b: '4' },
  pathname: '/a',
  path: '/a?a=3&b=4',
  href: '/a?a=3&b=4' }
coffee>

哦,我知道了,第一个true是把query变成JSON格式,第二个是把url解析成JSON格式,是么?

有道理。 只要是太菜了,看见这些单词组起来不知道什么意思,所以也不知道在怎么试。

@ggaaooppeenngg 这里只是第二个参数, 选项为 true 时多解析出了 query: { a: '3', b: '4' }, 第三个参数文档上比较明确, 是 //foo/bar 解析为 { host: 'foo', pathname: '/bar' } 或者 { pathname: '//foo/bar' } 的差别

回到顶部