require ( "path"). join을 사용하여 URL을 안전하게 연결할 수 있습니까?
다음과 같이 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'
그렇지 않다면 ifs로 가득 찬 코드를 작성하지 않고이 작업을 수행하는 방법은 무엇입니까?
아니요 path.join()
. URL과 함께 사용하면 잘못된 값을 반환합니다.
당신이 원하는 것 같은데 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'
편집 : Andreas가 의견에서 올바르게 지적했듯이 url.resolve
문제가 예제처럼 간단한 경우에만 도움이됩니다. url.parse
또한 URL
"ifs로 가득 찬 코드"의 필요성을 줄이는 객체를 통해 일관되고 예측 가능한 형식의 필드를 반환하기 때문에이 질문에도 적용됩니다 .
아니요, path.join()
URL 요소를 결합 하는 데 사용해서는 안됩니다 .
지금 그렇게하기위한 패키지가 있습니다. 따라서 바퀴를 재발 명하고, 모든 테스트를 작성하고, 버그를 찾고, 수정하고, 더 많은 테스트를 작성하고, 작동하지 않는 엣지 케이스를 찾는 등이 패키지를 사용할 수 있습니다.
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 '
아니! Windows path.join
에서는 백 슬래시로 결합됩니다. HTTP URL은 항상 슬래시입니다.
어때
> ["posts", "2013"].join("/")
'posts/2013'
URL 부분을 연결하기 위해 PATH를 시도했을 때 문제가 발생합니다. PATH.join
'//'를 '/'로 줄이면 절대 URL이 무효화됩니다 (예 : http : // ...-> http : / ...). 나에게 빠른 수정은 다음과 같습니다.
baseurl.replace(/\/$/,"") + '/' + path.replace(/^\//,"") )
또는 패닉 대령이 게시 한 솔루션 :
[pathA.replace(/^\/|\/$/g,""),pathB.replace(/^\/|\/$/g,"")].join("/")
우리는 다음과 같이합니다.
var _ = require('lodash');
function urlJoin(a, b) {
return _.trimEnd(a, '/') + '/' + _.trimStart(b, '/');
}
Axios 에는 URL을 결합 할 수있는 도우미 기능이 있습니다.
function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
}
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');
If you're using lodash, you can use this simple oneliner:
// returns part1/part2/part3
['part1/', '/part2', '/part3/'].map((s) => _.trim(s, '/')).join('/')
inspired by @Peter Dotchev's answer
If you use Angular, you can use 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.
Typescript custom solution:
export function pathJoin(parts: string[], sep: string) {
return parts
.map(part => {
const part2 = part.endsWith(sep) ? part.substring(0, part.length - 1) : part;
return part2.startsWith(sep) ? part2.substr(1) : part2;
})
.join(sep);
}
expect(pathJoin(['a', 'b', 'c', 'd'], '/')).toEqual('a/b/c/d');
expect(pathJoin(['a/', '/b/', 'c/', 'd'], '/')).toEqual('a/b/c/d');
expect(pathJoin(['http://abc.de', 'users/login'], '/')).toEqual('http://abc.de/users/login');
The WHATWG URL object constructor has a (input, base)
version, and the input
can be relative using /
, ./
, ../
. Combine this with path.posix.join
and you can do anything:
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'
참고URL : https://stackoverflow.com/questions/16301503/can-i-use-requirepath-join-to-safely-concatenate-urls
'development' 카테고리의 다른 글
Surefire는 Junit 5 테스트를 선택하지 않습니다. (0) | 2020.08.23 |
---|---|
속도를 높이기 위해 대용량 파일 (80GB)을 저장 하시겠습니까? (0) | 2020.08.23 |
const에 대한 Go 명명 규칙 (0) | 2020.08.23 |
JPA-persist () 후 자동 생성 된 ID 반환 (0) | 2020.08.23 |
R Markdown (Rmd 파일)의 텍스트 주석 처리 (0) | 2020.08.23 |