TIL | WIL
10/12 (목) Puppeteer에 발생한 CORS 문제 우회 성공 TIL, TIT
깊은바다거북
2023. 10. 12. 23:38
공부한 것
- LeetCode #106. Construct Binary Tree from Inorder and Postorder TraversalLeetCode - The World's Leading Online Programming Learning PlatformLevel up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/
ChatGPT에게 내가 푼 해답의 리팩토링을 부탁했는데 신기한 방식의 recursive 풀이가 나와 원리를 첨부한다:
코드 및 해설:
// 풀이3 function solution3(inorder: number[], postorder: number[]): TreeNode | null { function buildTree(inStart: number, inEnd: number, postStart: number, postEnd: number): TreeNode | null { if (inStart > inEnd || postStart > postEnd) { return null; } const rootVal = postorder[postEnd]; const root = new TreeNode(rootVal); const inorderIndex = inorder.indexOf(rootVal); root.left = buildTree(inStart, inorderIndex - 1, postStart, postStart + inorderIndex - 1 - inStart); root.right = buildTree(inorderIndex + 1, inEnd, postStart + inorderIndex - inStart, postEnd - 1); return root; /* 설명: * inorder: [9,3,15,20,7] * postorder:[9,15,7,20,3] * * 1. post에서 마지막 수 3은 반드시 root임을 확신할 수 있다. * 2. in에서 3의 위치를 찾는다. * 3. 3이 root이기 떄문에, 조상으로 뻗는 경우의 수는 모두 잘리고 in에서 3의 좌우로 위치하는 수들이 깔끔하게 왼 서브트리와 오른 서브트리로 나뉜다고 확신할 수 있다. * 4. 3을 root로 놓고 봤을 때, 왼 서브트리 전체는 1개의 노드(3)로 구성되어 있다. 오른 서브트리 전체는 3개의 노드(15,20,7)로 구성되어 있다. * 5. post를 구성한 원리가 '왼 서브트리 전체->오른 서브트리 전체->나(root)'의 순서임을 생각하면, 그냥 앞에서부터 차례로 세어서 왼 서브트리와 오른 서브트리 전체의 개수만큼 분리할 수 있다. 즉, post에서도 root 3의 왼 서브트리(9)와 오른 서브트리(15,7,20)를 확신있게 분리할 수 있는 것이다. * * 따라서 재귀호출을 순서대로 따라가보면 다음과 같이 분리된다: * inorder: [9,3,15,20,7] * postorder:[9,15,7,20,3] * * 1) root = 3 * inorder: [9] [] [15,20,7] * postorder:[9] [15,7,20] [] * 다음 호출: left([9],[9]) , right([15,20,7],[15,7,20]) * * 2) left root = 9, right root = 20 * inorder: [] [] [[15] [] [7]] * postorder:[] [[15] [7] []] [] * * 3) left root =15, right root = 7 * inorder: [] [] [[] [] []] * postorder:[] [[] [] []] [] */ } if (!inorder.length) return null; return buildTree(0, inorder.length - 1, 0, postorder.length - 1); }
진행 중
- puppeteer 라이브러리로 브라우저를 자동으로 열어 그래프를 그리는 html 파일을 실행하기 ✔️
- 하드코딩한 그래프 데이터를 실제 leetcode.com/api 서버에서 받아온 응답으로 대체하기
- cmd에서 $leetcode submission 관련 명령어로 puppeteer까지 실행되도록 연결하기
[Error] Access to script at ‘…’ from origin ‘null’ has been blocked by CORS policy ✔️
발생 상황:
puppeteer 라이브러리로 브라우저를 자동으로 열어 그래프를 그리려고 하는데, CORS 정책에 막혔다.
에러 메세지 전문:

시도:
- ⇒ CORS에 안 걸리려면 해당 graph.js 파일을 html파일에 넣을 때
<script type=”module” src=”pages/graph.js”>
태그 대신<script src=”pages/graph.js”>
와 같이 사용하여 graph.js 파일을 모듈로 인식하지 않도록 하면 된다.
- ⇒ 그러면 graph.js 파일 내부에서 ES6 모듈 방식인 import 키워드를 사용하는 대신 CommonJS 방식인 require 키워드를 사용해 타 파일을 임포트해야 한다.
- ⇒ 그러나 require 키워드는 기본적으로 브라우저가 인식하지 못한다.
해결:
graph.js 스크립트 파일 내부에서 require로 임포트해오는 코드를 아예 지워서 해결하였다. 필요한 함수를 하나의 graph.js 파일에 모아두어 단일 스크립트로 실행되게 만드니 어떤 에러도 나지 않고 잘 작동했다.
Uploaded by N2T