我可以使用require(“path”)。join来安全地连接网址吗?

时间:2013-04-30 13:45:36

标签: node.js url string-concatenation

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

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

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

如果没有,如果不编写完整的ifs代码,你会采用什么方式做这件事。

15 个答案:

答案 0 :(得分:103)

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

听起来你想要url.resolve。来自Node docs

url.resolve('/one/two/three', 'four')         // '/one/two/four'
url.resolve('http://example.com/', '/one')    // 'http://example.com/one'
url.resolve('http://example.com/one', '/two') // 'http://example.com/two'

修改 正如Andreas在评论中正确指出的那样,url.resolve只有在问题与示例一样简单的情况下才会有所帮助。 url.parse也适用于这个问题,因为它通过URL对象返回一致且可预测格式的字段,从而减少了“代码充满ifs”的需要。

答案 1 :(得分:32)

不,您不应使用path.join()加入网址元素。

现在有一个包这样做的包。因此,不是重新发明轮子,编写所有自己的测试,发现错误,修复错误,编写更多测试,找到不起作用的边缘情况等等,您可以使用此包。

URL联接

https://github.com/jfromaniello/url-join

安装

npm install url-join

用法

var urljoin = require('url-join');

var fullUrl = urljoin('http://www.google.com', 'a', '/b/cd', '?foo=123');

console.log(fullUrl);

打印:

' http://www.google.com/a/b/cd?foo=123'

答案 2 :(得分:6)

当我尝试使用PATH连接网址时,我遇到了问题。 PATH.join条纹'//'向下'/',这样会使绝对网址无效(例如http:// ... - > http:/ ...)。 对我来说,快速修复是:

baseurl.replace(/\/$/,"") + '/' + path.replace(/^\//,"") )

或由Panic上校发布的解决方案:

[pathA.replace(/^\/|\/$/g,""),pathB.replace(/^\/|\/$/g,"")].join("/")

答案 3 :(得分:5)

没有!在Windows path.join上将加入反斜杠。 HTTP网址总是正斜杠。

怎么样

> ["posts", "2013"].join("/")
'posts/2013'

答案 4 :(得分:5)

我们这样做:

var _ = require('lodash');

function urlJoin(a, b) {
  return _.trimEnd(a, '/') + '/' + _.trimStart(b, '/');
}

答案 5 :(得分:3)

这就是我使用的:

function joinUrlElements() {
  var re1 = new RegExp('^\\/|\\/$','g'),
      elts = Array.prototype.slice.call(arguments);
  return elts.map(function(element){return element.replace(re1,""); }).join('/');
}

示例:

url = joinUrlElements(config.mgmtServer, '/v1/o/', config.org, '/apps');

答案 6 :(得分:3)

这可以通过结合节点的pathURL来实现:

  1. 需要软件包:
const nodeUrl = require('url')
const nodePath = require('path')
  1. 首先创建一个URL对象以供使用:
> const myUrl = new nodeUrl.URL('https://example.com')
  1. 使用pathname=path.join构建任何可能的组合:
> myUrl.pathname = nodePath.join('/search', 'for', '/something/')
'/search/for/something/'

(您可以看到带有参数的path.join的自由度

  1. 此时,您的URL反映了最终的预期结果:
> myUrl.toString()
'https://example.com/search/for/something/'

为什么要使用这种方法?

此技术使用内置库。在CVE,维护等方面,第三方依赖性越少越好。

PS:切勿将URL当作字符串来处理!

当我查看代码时,我坚信永远不要手动将URL操纵为字符串。首先,看看the spec is有多复杂。

第二,缺少/存在尾部/前缀的斜杠(/)不会导致一切中断!您绝对不应该这样做:

const url = `${baseUrl}/${somePath}`

,尤其是:

uri: host + '/' + SAT_SERVICE + '/' + CONSTELLATION + '/',

我见过的

答案 7 :(得分:2)

如果你使用 lodash ,你可以使用这个简单的oneliner:

try { 
    $dt = new \DateTime('0000-00-00 00:00:00'); 
} catch (Exception $e) { 
    var_dump($e); 
}
@Peter Dotchev的回答

的启发

答案 8 :(得分:2)

Axios 有一个可以组合网址的辅助功能。

function combineURLs(baseURL, relativeURL) {
  return relativeURL
    ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
    : baseURL;
}
  

来源:   https://github.com/axios/axios/blob/fe7d09bb08fa1c0e414956b7fc760c80459b0a43/lib/helpers/combineURLs.js

答案 9 :(得分:2)

如果使用Angular,则可以使用Location

import { Location } from '@angular/common';
// ...
Location.joinWithSlash('beginning', 'end');

尽管只能处理2个参数,所以如果需要,您必须链接调用或编写一个辅助函数来完成此操作。

答案 10 :(得分:1)

WHATWG URL object构造函数具有(input, base)版本,并且input可以使用/./../是相对的。将其与path.posix.join结合使用,您可以执行任何操作:

const {posix} = require ("path");
const withSlash = new URL("https://example.com:8443/something/");
new URL(posix.join("a", "b", "c"), withSlash).toString(); // 'https://example.com:8443/something/a/b/c'
new URL(posix.join("./a", "b", "c"), withSlash).toString(); // 'https://example.com:8443/something/a/b/c'
new URL(posix.join("/a", "b", "c"), withSlash).toString(); // 'https://example.com:8443/a/b/c'
new URL(posix.join("../a", "b", "c"), withSlash).toString(); // 'https://example.com:8443/a/b/c'
const noSlash = new URL("https://example.com:8443/something");
new URL(posix.join("./a", "b", "c"), noSlash).toString(); // 'https://example.com:8443/a/b/c'

答案 11 :(得分:1)

还有其他可行的答案,但我同意以下内容。一点路径。join/ URL组合。

const path = require('path');
//
const baseUrl = 'http://ejemplo.mx';
// making odd shaped path pieces to see how they're handled.
const pieces = ['way//', '//over/', 'there/'];
//
console.log(new URL(path.join(...pieces), baseUrl).href);
// http://ejemplo.mx/way/over/there/

// path.join expects strings. Just an example how to ensure your pieces are Strings.
const allString = ['down', 'yonder', 20000].map(String);
console.log(new URL(path.join(...allString), baseUrl).href);
// http://ejemplo.mx/down/yonder/20000

答案 12 :(得分:0)

打字稿自定义解决方案:

String jsonsDataString = responseJson.toString();
final jsonData = jsonDecode(jsonsDataString);

//then you can get your values from the map
if(jsonData[AuthUtils.authTokenKey] != null){
...
}

答案 13 :(得分:0)

我的解决方案

path.join(SERVER_URL, imageAbsolutePath).replace(':/','://');

编辑:如果要支持Windows环境

path.join(SERVER_URL, imageAbsolutePath).replace(/\\/g,'/').replace(':/','://');

第二种解决方案将替换所有的反斜杠,因此url部分(例如querystring和hash)也可能会发生变化,但是本主题仅连接了url路径,因此我认为这不是问题。

答案 14 :(得分:0)

不建议发布此答案url.resolve()

我做了以下工作以加入Node.js中的路径:

const path = require('path');
const url = require('url');


let myUrl = new URL('http://ignore.com');
myUrl.pathname=path.join(firstpath, secondpath);
console.log(myUrl.pathname)

这种方法记录正确的url路径,并且适用于我的情况。

您对此方法有何看法?

谢谢