>  기사  >  웹 프론트엔드  >  URL 객체

URL 객체

Mary-Kate Olsen
Mary-Kate Olsen원래의
2024-10-11 10:36:29279검색

The URL Object

개요

JavaScript의 URL 개체는 URL을 쉽게 사용하고 조작할 수 있는 방법을 제공합니다. 코드 내에서 URL을 생성, 구문 분석 또는 수정해야 할 때 특히 유용합니다.

JavaScript에서 URL을 생성하기 위해 템플릿 문자열이 사용되는 경우가 많습니다. 종종 이는 쉽고 명확하지만 URL 객체는 URL을 처리하는 보다 강력한 OOP 방법입니다.

OpenWeatherMap.org도 문서에서 템플릿 문자열을 사용합니다. https://api.openweathermap.org/data/3.0/onecall?lat={lat}&lon={lon}&exclude={part}&appid={API 키 }

상당히 정적인 URL의 경우에는 괜찮지만, 이 URL을 변경하려면 URL 개체 사용을 고려해 보세요.

// Using template strings
const lat = 32.087;
const lon = 34.801;
const apiKey = 'your_api_key';
const url = `https://api.openweathermap.org/data/3.0/onecall?lat=${lat}&lon=${lon}&appid=${apiKey}`;

// Using the URL object
const openWeatherUrl = new URL('https://api.openweathermap.org/data/3.0/onecall');
openWeatherUrl.searchParams.set('lat', lat);
openWeatherUrl.searchParams.set('lon', lon);
openWeatherUrl.searchParams.set('appid', apiKey);

기본 사용법

URL 문자열을 생성자에 전달하여 새 URL 개체를 생성할 수 있습니다.

이 경우(위와 반대로) 전체 URL이 다양한 부분과 함께 전달됩니다.

const url = new URL('https://example.com:8080/path?query=123#section');

속성

URL 개체에는 URL의 일부에 액세스하는 데 사용할 수 있는 여러 속성이 있습니다.

  • href: 문자열로 된 전체 URL입니다.
  • 프로토콜: 프로토콜(예: https:).
  • 호스트 이름: 도메인 이름(예: example.com).
  • port: 포트 번호(예: 8080).
  • 경로명: 도메인 다음 경로(예: /path).
  • 검색: ?를 포함한 쿼리 문자열입니다. (예: ?query=123).
  • 해시: #(예: #section)을 포함한 조각 식별자입니다.
  • 호스트: 호스트 이름과 포트가 결합된 것입니다(예: example.com:8080).
  • Origin: 프로토콜, 호스트 이름, 포트인 URL의 출처입니다.
> const url = new URL('https://example.com:8080/path?query=123#section');
> url.port
'8080'
> url.protocol
'https:'
> url.hostname
'example.com'
> url.pathname
'/path'
> url.search
'?query=123'
> url.hash
'#section'
> url.host
'example.com:8080'

URL의 다른 부분을 변경하는 데에도 사용할 수 있습니다.

> url.port = 1234
1234
> url.pathname = "differentpath"
'differentpath'
> url.hostname = "example.org"
'example.org'
> url
URL {
  href: 'https://example.org:1234/differentpath?query=123#section',
  origin: 'https://example.org:1234',
  protocol: 'https:',
  username: '',
  password: '',
  host: 'example.org:1234',
  hostname: 'example.org',
  port: '1234',
  pathname: '/differentpath',
  search: '?query=123',
  searchParams: URLSearchParams { 'query' => '123' },
  hash: '#section'
}

행동 양식

URL 개체에는 URL을 수정하고 상호 작용하는 데 도움이 되는 몇 가지 메서드도 있습니다.

예를 들어 URL 검색 매개변수는 사용자에게 서비스를 제공하기 위해 API 서버 세부정보를 알려주는 키와 값 쌍입니다.

url.searchParams: 쿼리 문자열 매개변수를 사용하는 방법을 제공하는 URLSearchParams 개체를 반환합니다. 다음을 수행할 수 있습니다.

쿼리 매개변수 가져오기: url.searchParams.get('query')
쿼리 매개변수 설정: url.searchParams.set('query', '456')
쿼리 매개변수 삭제: url.searchParams.delete('query')

쿼리 매개변수 반복:

url.searchParams.forEach((value, key) => {
  console.log(key, value);
});

toString(): 속성 또는 쿼리 매개변수에 대한 변경 사항을 반영하여 전체 URL을 문자열로 반환합니다.

Open Weather Map API의 예

다음은 OpenWeatherMap 문서입니다: https://openweathermap.org/api/one-call-3

다음은 URL 객체를 생성하고 해당 부분을 조작하는 방법을 보여주는 간단한 예입니다.

// get values to interpolate to URL
const apiKey = process.env.openWeatherApiKey || 0
const [lat, lon] = [32.08721095615897, 34.801588162316506]

const openWeatherUrl = new URL("https://api.openweathermap.org")

openWeatherUrl.pathname = "data/3.0/onecall"
openWeatherUrl.searchParams.set('lat',lat)
openWeatherUrl.searchParams.set('lon',lon)

// from the docs
openWeatherUrl.searchParams.set('exclude', 'hourly')

openWeatherUrl.searchParams.set('appid', apiKey)

console.log(openWeatherUrl)

출력:

URL {
  href: 'https://api.openweathermap.org/data/3.0/onecall?lat=32.08721095615897&lon=34.801588162316506&exclude=hourly&appid=0',
  origin: 'https://api.openweathermap.org',
  protocol: 'https:',
  username: '',
  password: '',
  host: 'api.openweathermap.org',
  hostname: 'api.openweathermap.org',
  port: '',
  pathname: '/data/3.0/onecall',
  search: '?lat=32.08721095615897&lon=34.801588162316506&exclude=hourly&appid=0',
  searchParams: URLSearchParams {
    'lat' => '32.08721095615897',
    'lon' => '34.801588162316506',
    'exclude' => 'hourly',
    'appid' => '0' },
  hash: ''
}

요약

JavaScript의 URL 객체는 URL 작업을 위한 구조화된 방법을 제공하므로 복잡한 URL을 쉽게 조작하고 구성할 수 있습니다. 템플릿 문자열은 정적 URL에 간단하고 효과적이지만, URL 객체는 URL이 동적이거나 자주 수정해야 하는 경우에 이상적입니다.


사진: Anne Nygård, Unsplash

위 내용은 URL 객체의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.