gpt4 book ai didi

javascript - 如何在nodejs url解析中包含端口

转载 作者:可可西里 更新时间:2023-11-01 17:10:08 33 4
gpt4 key购买 nike

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

我有两个字符串:

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/

有什么建议吗?

谢谢!

最佳答案

如果比较以下两个调用,您会发现在字符串前面添加协议(protocol)会产生很大的不同:

> 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' }
>

您可能正在寻找的是添加协议(protocol),然后使用 + 而不是 :

> 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/' }
>

关于javascript - 如何在nodejs url解析中包含端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22700336/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com