node.js 我可以使用 require("path").join 来安全地连接 urls 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16301503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I use require("path").join to safely concatenate urls?
提问by Renato Gama
Is this safe to use require("path").jointo concatenate URLs, for example:
require("path").join用于连接 URL是否安全,例如:
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 not, what way would you suggest for doing this without writing code full of ifs?
如果没有,你会建议用什么方法来做这件事而不编写充满 ifs 的代码?
回答by Matthew Bakaitis
No. path.join()will return incorrect values when used with URLs.
No. path.join()与 URL 一起使用时将返回不正确的值。
It sounds like you want url.resolve. From the Node docs:
听起来你想要url.resolve。从节点文档:
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'
Edit:As Andreas correctly points out in a comment, url.resolvewould only help if the problem is as simple as the example. url.parsealso applies to this question because it returns consistently and predictably formatted fields via the URLobject that reduces the need for "code full of ifs".
编辑:正如 Andreas 在评论中正确指出的那样,url.resolve只有当问题像示例一样简单时才会有所帮助。 url.parse也适用于这个问题,因为它通过URL对象返回一致且可预测的格式字段,从而减少了“充满 ifs 的代码”的需要。
回答by stone
No, you should not use path.join()to join URL elements.
不,您不应该使用path.join()连接 URL 元素。
There's a package for doing that now. So rather than reinvent the wheel, write all your own tests, find bugs, fix them, write more tests, find an edge case where it doesn't work, etc., you could use this package.
现在有一个包可以做到这一点。因此,与其重新发明轮子,编写所有自己的测试,查找错误,修复它们,编写更多测试,找到它不起作用的边缘情况等,您可以使用这个包。
url-join
网址连接
https://github.com/jfromaniello/url-join
https://github.com/jfromaniello/url-join
Install
安装
npm install url-join
npm install url-join
Usage
用法
var urljoin = require('url-join');
var fullUrl = urljoin('http://www.google.com', 'a', '/b/cd', '?foo=123');
console.log(fullUrl);
Prints:
印刷:
回答by Ikbel
Axioshas a helper function that can combine URLs.
Axios有一个辅助函数,可以组合 URL。
function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
}
来源:https: //github.com/axios/axios/blob/fe7d09bb08fa1c0e414956b7fc760c80459b0a43/lib/helpers/combineURLs.js
回答by Peter
When I tried PATH for concatenating url parts I run into problems.
PATH.joinstripes '//' down to '/' and this way invalidates an absolute url (eg. http://... -> http:/...).
For me a quick fix was:
当我尝试使用 PATH 连接 url 部分时,我遇到了问题。
PATH.join条纹 '//' 到 '/' 并且这种方式使绝对 url 无效(例如 http://... -> http://...)。对我来说,快速解决方法是:
baseurl.replace(/\/$/,"") + '/' + path.replace(/^\//,"") )
or with the solution posted by Colonel Panic:
或使用恐慌上校发布的解决方案:
[pathA.replace(/^\/|\/$/g,""),pathB.replace(/^\/|\/$/g,"")].join("/")
回答by Colonel Panic
No! On Windows path.joinwill join with backslashes. HTTP urls are always forward slashes.
不!在 Windowspath.join上将加入反斜杠。HTTP url 总是正斜杠。
How about
怎么样
> ["posts", "2013"].join("/")
'posts/2013'
回答by Peter Dotchev
We do it like this:
我们这样做:
var _ = require('lodash');
function urlJoin(a, b) {
return _.trimEnd(a, '/') + '/' + _.trimStart(b, '/');
}
回答by Cheeso
This is what I use:
这是我使用的:
function joinUrlElements() {
var re1 = new RegExp('^\/|\/$','g'),
elts = Array.prototype.slice.call(arguments);
return elts.map(function(element){return element.replace(re1,""); }).join('/');
}
example:
例子:
url = joinUrlElements(config.mgmtServer, '/v1/o/', config.org, '/apps');
回答by Qortex
If you use Angular, you can use Location:
如果您使用 Angular,则可以使用Location:
import { Location } from '@angular/common';
// ...
Location.joinWithSlash('beginning', 'end');
Works only on 2 arguments though, so you have to chain calls or write a helper function to do that if needed.
虽然只适用于 2 个参数,因此如果需要,您必须链接调用或编写一个辅助函数来执行此操作。
回答by M K
If you're using lodash, you can use this simple oneliner:
如果你使用lodash,你可以使用这个简单的 oneliner:
// returns part1/part2/part3
['part1/', '/part2', '/part3/'].map((s) => _.trim(s, '/')).join('/')
inspired by @Peter Dotchev'sanswer
受到@Peter Dotchev回答的启发
回答by Coderer
The WHATWG URL objectconstructor has a (input, base)version, and the inputcan be relative using /, ./, ../. Combine this with path.posix.joinand you can do anything:
在WHATWG URL对象的构造函数有一个(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'

