我可以使用 require("path").join 来安全地连接 urls 吗? [英] Can I use require("path").join to safely concatenate urls?

查看:39
本文介绍了我可以使用 require("path").join 来安全地连接 urls 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 require("path").join 连接 URL 是否安全,例如:

Is this safe to use require("path").join to concatenate URLs, for example:

require("path").join("http://example.com", "ok"); 
//returns 'http://example.com/ok'

require("path").join("http://example.com/", "ok"); 
//returns 'http://example.com/ok'

如果不是,您会建议如何在不编写充满 if 的代码的情况下执行此操作?

If not, what way would you suggest for doing this without writing code full of ifs?

推荐答案

没有.path.join() 与 URL 一起使用时将返回错误的值.

No. path.join() will return incorrect values when used with URLs.

听起来你想要new URL().来自 WHATWG URL 标准:

It sounds like you want new URL(). From the WHATWG URL Standard:

new URL('/one', 'http://example.com/').href    // 'http://example.com/one'
new URL('/two', 'http://example.com/one').href // 'http://example.com/two'

请注意,url.resolve 现在在 节点中被标记为已弃用文档.

正如 Andreas 在评论中正确指出的那样,url.resolve(还有 deprecated) 只有在问题像示例一样简单时才会有所帮助.url.parse 也适用于这个问题,因为它通过 URL 对象返回一致且可预测的格式字段,从而减少了充满 ifs 的代码"的需要.但是,new URL() 也是 url.parse 的替代品.

As Andreas correctly points out in a comment, url.resolve (also deprecated) would only help if the problem is as simple as the example. url.parse also applies to this question because it returns consistently and predictably formatted fields via the URL object that reduces the need for "code full of ifs". However, new URL() is also the replacement for url.parse.

这篇关于我可以使用 require("path").join 来安全地连接 urls 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆