In node.js how to get/construct URL string from WHATWG URL including user and password but nothing after host

空扰寡人 提交于 2020-01-26 04:05:27

问题


What would be the recommended way of deriving the following:

https://user:pass@hostname:port

From:

https://user:pass@hostname:port/p/a/t/h?q=whatevere#hash

when dealing with node.js url module using current WHATWG URL ?


回答1:


Pretty sure you can use standard javascript with node.js

  var s = 'https://user:pass@hostname:port/path#hash';
  s = s.substring(0, s.lastIndexOf('/'));

That should give you s as the value you want.

Caz

Update -

You could also do this if you can't predict the number of / in the URL

var url = 'https://user:pass@hostname:port/p/a/t/h?q=whatevere#hash';
url = url.split( '/' )[2];

What that does is creates an array from that string using / as the deliminator. So url[0] would be https: url[1] would be blank as its between the two / and url[2] will be user:pass@hostname:port

So if you don't need the http part you can do that and even do something like this is the https is important

var url = 'https://user:pass@hostname:port/p/a/t/h?q=whatevere#hash';
url = url.split( '/' )[2];
var urlstring = 'https://' + url 



回答2:


As of Node 8.x with the WHATWG URL API:

const { URL } = require('url');
const url = new URL('https://user:pass@hostname:1234/p/a/t/h?q=whatevere#hash');
url.search = url.pathname = url.hash = '';
console.log(url.toString()); // https://user:pass@hostname:1234/


来源:https://stackoverflow.com/questions/45047840/in-node-js-how-to-get-construct-url-string-from-whatwg-url-including-user-and-pa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!