programing

require("path")를 사용할 수 있습니까?URL을 안전하게 연결하기 위해 가입합니까?

mailnote 2023. 9. 13. 22:53
반응형

require("path")를 사용할 수 있습니까?URL을 안전하게 연결하기 위해 가입합니까?

안전하게 사용할 수 있습니까?require("path").joinURL을 연결하려면 다음과 같이

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과 함께 사용하면 잘못된 값을 반환합니다.

당신이 원하는 것처럼 들립니다.new URL(). WHATWG URL 표준에서:

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이제 Node 문서에서 사용하지 않는 것으로 표시됩니다.

처럼, ,url.resolve(또한 사용되지 않음)은 예제처럼 문제가 간단한 경우에만 도움이 됩니다.url.parse한이에됩니다를 통해 에 이 됩니다. 왜냐하면 그것은 일관성 있고 예측 가능하게 포맷된 필드를 를 통해 반환하기 때문입니다.URL" of ifs의 필요성을 .ifs로득찬드의을체는체는을ttresd"elf만,new URL()의도다의 .url.parse.

아니요, 사용하시면 안 됩니다.path.join()URL 요소에 가입합니다.

지금 그렇게 할 수 있는 소포가 있습니다.따라서 휠을 재창조하고, 모든 테스트를 작성하고, 버그를 찾고, 수정하고, 더 많은 테스트를 작성하고, 작동하지 않는 에지 케이스를 찾는 등의 방법으로 이 패키지를 사용할 수 있습니다.

url-layout

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'

노드의 경로URL의 조합을 통해 이 작업을 수행할 수 있습니다.

  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, 유지보수 등과 관련해서는 타사 의존성이 적을수록 좋습니다.

표준 입술보다 더 검증되거나 더 잘 검증된 것은 없을 것입니다.

추신: URL을 문자열로 조작하지 마십시오!

코드를 검토할 때 URL을 수동으로 문자열로 조작하지 않는 에 대해 단호합니다.우선, 스펙이 얼마나 복잡한지 보세요.

슬래시의 (, / 의/()/이 깨져서는 모든 것이 부서지게 해서는 안 됩니다!절대로 하면 안 됩니다.

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

특히 그렇지 않습니다.

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

그 중에서 제가 본 것입니다.

액시오스에는 URL을 결합할 수 있는 도우미 기능이 있습니다.

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

출처 : https://github.com/axios/axios/blob/fe7d09bb08fa1c0e414956b7fc760c80459b0a43/lib/helpers/combineURLs.js

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'

Angular를 사용하는 경우 Location:

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

그러나 두 개의 인수에서만 작동하므로 필요한 경우 통화를 연결하거나 도우미 기능을 작성해야 합니다.

아니요! 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, '/');
}

lodash를 사용하는 경우, 다음과 같은 간단한 한 줄기를 사용할 수 있습니다.

// returns part1/part2/part3
['part1/', '/part2', '/part3/'].map((s) => _.trim(s, '/')).join('/')

@피터 닷체프의 대답에 고무되어

이것이 제가 사용하는 것입니다.

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');

다른 실무적인 답변들도 있지만, 저는 다음과 같이 진행했습니다.작은 경로.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

이 답변을 게시할 때까지.url.resolve()감가 상각됩니다.

Nodejs의 경로에 가입하기 위해 다음과 같이 했습니다.

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 경로를 기록하며 내 경우에 적합합니다.

이 접근법에 대한 당신의 의견은 어떻습니까?

감사해요.

스크립트 사용자 지정 솔루션:

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');

나의 해결책

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

편집: Windows 환경을 지원하려면

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

두 번째 솔루션은 백슬래시를 모두 대체하기 때문에 querystring이나 hash와 같은 url 부분도 변경될 수 있지만, url path만 결합하는 것이 주제이기 때문에 문제가 되지 않는다고 생각합니다.

기본 제공 경로와 URL 라이브러리의 조합이 최상의 솔루션을 제공합니다.

그러나 위의 답변에서는 기존 URL(즉, "http://example.com/test/bar ")에 추가할 상대 URL(즉, "../foo")이 있는 경우는 다루지 않습니다.단순하게 하기new URL("../foo","http://example.com/test/bar").href원래 경로의 나머지를 버리면 "http://example.com/foo "이 생성됩니다.

간단한 해결책은 다음과 같습니다.

var base = "http://example.com:8080/foo/bar";
var rel = "../test";
var resolved = new URL( path.resolve(new URL(base).pathname, rel ), base ).href;
// Result: http://example.com:8080/foo/test

참고: URL 검색 매개 변수(이 시나리오에서는 불가능한 것으로 보임)를 고려하는 경우 위의 각 조각을 개별 변수에 저장하고 새 값을 설정합니다.url.searchParams = oldUrl.searchParamshref 출력을 얻기 전에.

언급URL : https://stackoverflow.com/questions/16301503/can-i-use-requirepath-join-to-safely-concatenate-urls

반응형