关于 url.format() 的使用
发布于 7 年前 作者 g8up 3920 次浏览 来自 问答

问题:格式化一个 url 时,设置的端口不生效。

var url = require('url');
var u = 'http://getcrx.cn/';

var parsed = url.parse( u );
console.log( 'url.parse----', parsed );

parsed.port = 80; // 设置端口
parsed.path = '/index.html';
console.log( 'url.format----', url.format( parsed ) );// 期望 'http://getcrx.cn:80/index.html'

输出的结果却是:

url.parse---- Url {
  protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'getcrx.cn',
  port: null,
  hostname: 'getcrx.cn',
  hash: null,
  search: null,
  query: null,
  pathname: '/',
  path: '/',
  href: 'http://getcrx.cn/' }
url.format---- http://getcrx.cn/

是姿势不对吗?

1 回复

自答:

var url = require('url');

var u = 'http://getcrx.cn/';

var parsed = url.parse( u );
console.log( 'url.parse----', parsed );

parsed.host = ''; // 发现需要清除一下 host
parsed.port = 80;
parsed.pathname = '/index.html';

console.log( 'url.format----', url.format( parsed ) );// 期望 'http://getcrx.cn:80/index.html'

灵感来自: untitled1.png API

回到顶部