url 모듈에서 검색 문자열 업데이트

6229 단어 Node.js

개시하다


URL 문자열을 조작할 때, 텍스트 열 작업 대신 전용 프로그램 라이브러리를 사용하려고 합니다.문자열 작업 중 형식이 올바르지 않은 문자열을 만들 위험이 있기 때문입니다.예를 들어 검색 문자열 ? 을 추가하는 것을 잊었습니다.
Node.js에 url 모듈이 존재합니다.이 모듈을 사용하면 URL 문자열의 해석과 생성을 간단하게 할 수 있습니다.그러나 기존 URL 문자열의 쿼리 문자열을 가공하려다 의외로 힘들어 이번에 노트를 남겼다.

메서드

import 'url';

const addQueryTo = (href, query) => {
  const urlObject = url.parse(href, true); // (1)

  urlObject.search = undefined; // (2)
  Object.assign(urlObject.query, query);

  return url.format(urlObject);
};

addQueryTo('http://example.com', { hoge: 1 });
//=> 'http://example.com/?hoge=1'

addQueryTo('http://example.com?hoge=1', { fuga: 2 });
//=> 'http://example.com/?hoge=1&fuga=2'

addQueryTo('http://example.com?hoge=1', { hoge: 10, fuga: 20 });
//=> 'http://example.com/?hoge=10&fuga=20'
포인트가 두 개 있어요.

(1) url.트루 값이 parse()인 두 번째 매개변수 지정하기


parseQueryString If true, the query property will always be set to an object returned by the querystring module's parse() method.
이렇게 하면 검색 문자열은 querystring 모듈에 의해 제거되고 대상으로 처리할 수 있습니다.객체로서 업데이트와 병합 등의 작업이 간단해집니다.

(2) urlObject.검색에 undefined를 대입하다


이것은 중요한 점이다.
If the urlObject.search property is undefined and if the urlObject.query property is an Object, the literal string ? is appended to result followed by the output of calling the querystring module's stringify() method passing the value of urlObject.query.urlObject.searchundefined인 경우에만 url.format()의 결과가 반영urlObject.query된다.이외에도 urlObject.search의 값을 사용하면 아무리 업데이트urlObject.query해도 url.format()의 결과에 반영되지 않는다.
const urlObject = url.parse('http://example.com?hoge=1', true);

urlObject.query  //=> { hoge: '1' }
urlObject.search //=> '?hoge=1'

Object.assign(urlObject.query, { fuga: 2 });

urlObject.query  //=> { hoge: '1', fuga: 2 }
urlObject.search //=> '?hoge=1'

url.format(urlObject) //=> 'http://example.com/?hoge=1'
문서를 제대로 읽지 못해서 이 스타일에 빠지기가 힘들어

참고 자료

  • 공식 문서
  • Node.js v7.7.3 Documentation > URL
  • Stack Overflow

  • Node.js url.parse result back to string
  • 좋은 웹페이지 즐겨찾기