Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problem with require #17

Closed
be9904 opened this issue May 23, 2021 · 6 comments
Closed

Problem with require #17

be9904 opened this issue May 23, 2021 · 6 comments
Assignees
Labels
bug Something isn't working

Comments

@be9904
Copy link
Owner

be9904 commented May 23, 2021

크롤링 파일에 있는 require node 모듈이 브라우저로 실행이 안됩니다.
혹시 해결책 아시는 분은 여기에 댓글이나 링크 남겨주세요

Uncaught Error: Mismatched anonymous define() module: function(){"use strict";const t=t=>{do{t+=Math.floor(1e6Math.random())}while(document.getElementById(t));return t},e=t=>{let e=t.getAttribute("data-bs-target");if(!e||"#"===e){let i=t.getAttribute("href");if(!i||!i.includes("#")&&!i.startsWith("."))return null;i.includes("#")&&!i.startsWith("#")&&(i="#"+i.split("#")[1]),e=i&&"#"!==i?i.trim():null}return e},i=t=>{const i=e(t);return i&&document.querySelector(i)?i:null},s=t=>{const i=e(t);return i?document.querySelector(i):null},n=t=>{if(!t)return 0;let{transitionDuration:e,transitionDelay:i}=window.getComputedStyle(t);const s=Number.parseFloat(e),n=Number.parseFloat(i);return s||n?(e=e.split(",")[0],i=i.split(",")[0],1e3(Number.parseFloat(e)+Number.parseFloat(i))):0},o=t=>{t.dispatchEvent(new Event("transitionend"))},r=t=>(t[0]||t).nodeType,a=(t,e)=>{let i=!1;const s=e+5;t.addEventListener("transitionend",(function e(){i=!0,t.removeEventListener("transitionend",e)})),setTimeout(()=>{i||o(t)},s)},l=(t,e,i)=>{Object.keys(i).forEach(s=>{const n=i[s],o=e[s],a=o&&r(o)?"element":null==(l=o)?""+l:{}.toString.call(l).match(/\s([a-z]+)/i)[1].toLowerCase();var l;if(!new RegExp(n).test(a))throw new TypeError(t.toUpperCase()+": "+Option "${s}" provided type "${a}" +but expected type "${n}".)})},c=t=>{if(!t)return!1;if(t.style&&t.parentNode&&t.parentNode.style){const e=getComputedStyle(t),i=getComputedStyle(t.parentNode);return"none"!==e.display&&"none"!==i.display&&"hidden"!==e.visibility}return!1},d=t=>!t||t.nodeType!==Node.ELEMENT_NODE||!!t.classList.contains("disabled")||(void 0!==t.disabled?t.disabled:t.hasAttribute("disabled")&&"false"!==t.getAttribute("disabled")),h=t=>{if(!document.documentElement.attachShadow)return null;if("function"==typeof t.getRootNode){const e=t.getRootNode();return e instanceof ShadowRoot?e:null}return t instanceof ShadowRoot?t:t.parentNode?h(t.parentNode):null},f=()=>function(){},u=t=>t.offsetHeight,p=()=>{const{jQuery:t}=window;return t&&!document.body.hasAttribute("data-bs-no-jquery")?t:null},g=()=>"rtl"===document.documentElement.dir,m=(t,e)=>{var i;i=()=>{const i=p();if(i){const s=i.fn[t];i.fn[t]=e.jQueryInterface,i.fn[t].Constructor=e,i.fn[t].noConflict=()=>(i.fn[t]=s,e.jQueryInterface)}},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",i):i()},=new Map;var b={set(t,e,i){.has(t)||.set(t,new Map);const s=.get(t);s.has(e)||0===s.size?s.set(e,i):console.error(Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(s.keys())[0]}.)},get:(t,e)=>.has(t)&&.get(t).get(e)||null,remove(t,e){if(!.has(t))return;const i=.get(t);i.delete(e),0===i.size&&_.delete(t)}};const v=/[^.](?=..).|./,y=/../,w=/::\d+$/,E={};let T=1;const A={mouseenter:"mouseover",mouseleave:"mouseout"},L=new Set(["click","dblclick","mouseup","mousedown","contextmenu","mousewheel","DOMMouseScroll","mouseover","mouseout","mousemove","selectstart","selectend","keydown","keypress","keyup","orientationchange","touchstart","touchmove","touchend","touchcancel","pointerdown","pointermove","pointerup","pointerleave","pointercancel","gesturestart","gesturechange","gestureend","focus","blur","change","reset","select","submit","focusin","focusout","load","unload","beforeunload","resize","move","DOMContentLoaded","readystatechange","error","abort","scroll"]);function O(t,e){return e&&${e}::${T++}||t.uidEvent||T++}function k(t){const e=O(t);return t.uidEvent=e,E[e]=E[e]||{},E[e]}function D(t,e,i=null){const s=Object.keys(t);for(let n=0,o=s.length;n<o;n++){const o=t[s[n]];if(o.originalHandler===e&&o.delegationSelector===i)return o}return null}function x(t,e,i){const s="string"==typeof e,n=s?i:e;let o=t.replace(y,"");const r=A[o];return r&&(o=r),L.has(o)||(o=t),[s,n,o]}function C(t,e,i,s,n){if("string"!=typeof e||!t)return;i||(i=s,s=null);const[o,r,a]=x(e,i,s),l=k(t),c=l[a]||(l[a]={}),d=D(c,r,o?i:null);if(d)return void(d.oneOff=d.oneOff&&n);const h=O(r,e.replace(v,"")),f=o?function(t,e,i){return function s(n){const o=t.querySelectorAll(e);for(let{target:e}=n;e&&e!==this;e=e.parentNode)for(let r=o.length;r--;)if(o[r]===e)return n.delegateTarget=e,s.oneOff&&N.off(t,n.type,i),i.apply(e,[n]);return null}}(t,i,s):function(t,e){return function i(s){return s.delegateTarget=t,i.oneOff&&N.off(t,s.type,e),e.apply(t,[s])}}(t,i);f.delegationSelector=o?i:null,f.originalHandler=r,f.oneOff=n,f.uidEvent=h,c[h]=f,t.addEventListener(a,f,o)}function S(t,e,i,s,n){const o=D(e[i],s,n);o&&(t.removeEventListener(i,o,Boolean(n)),delete e[i][o.uidEvent])}const N={on(t,e,i,s){C(t,e,i,s,!1)},one(t,e,i,s){C(t,e,i,s,!0)},off(t,e,i,s){if("string"!=typeof e||!t)return;const[n,o,r]=x(e,i,s),a=r!==e,l=k(t),c=e.startsWith(".");if(void 0!==o){if(!l||!l[r])return;return void S(t,l,r,o,n?i:null)}c&&Object.keys(l).forEach(i=>{!function(t,e,i,s){const n=e[i]||{};Object.keys(n).forEach(o=>{if(o.includes(s)){const s=n[o];S(t,e,i,s.originalHandler,s.delegationSelector)}})}(t,l,i,e.slice(1))});const d=l[r]|require.js:110)

@ChanuYu ChanuYu added the bug Something isn't working label May 23, 2021
@ChanuYu
Copy link
Collaborator

ChanuYu commented May 23, 2021

첨부하신 게 다 에러코드인가요?

@ChanuYu
Copy link
Collaborator

ChanuYu commented May 23, 2021

제 생각에 결론부터 말씀드리자면

const parser = require("node-html-parser");

이 부분을 지우시면 해결할 수 있을 거 같아요. 확실하진 않습니다.
Mismatched anonymous define() module: 이 에러 코드로 구글링 해보니 require가 어떤 상황에서 제대로 동작하지 않는 거 같아요 참고사이트

https.get(
    url,
    {
        headers: {
            "User-Agent": User_Agent,
        },
    },
    (res) => {
        let data = "";

        res.on("data", (d) => {
            data += d;
        });

        res.on("end", () => {
            let expression = new RegExp("var jsonData = {.*};");
            let jsonarr = expression.exec(data);
            let text = jsonarr[0].split("=");

            jsondata = JSON.parse(text[1].trim().slice(0, -1));
            console.log(jsondata);
        });
    }
);

어차피 여기서 보시면 url의 데이터를 html 코드로 parse를 하지 않으니 지우셔도 무방할 겁니다.

해결 안 되면 다시 말해주세요.

@be9904
Copy link
Owner Author

be9904 commented May 23, 2021

해결방법 찾아보다가 Github에 Browserify 모듈 써봤는데 일단 오류는 전부 사라졌습니다.
근데 아직 코드가 완성 상태는 아니라 나중에 문제가 또 생길 수 있으니 이슈는 열어놓을게요

@be9904
Copy link
Owner Author

be9904 commented May 23, 2021

말씀해주신 node-html-parser도 확인해보니 사용되고 있지 않은 모듈이어서 삭제했습니다.

@ChanuYu
Copy link
Collaborator

ChanuYu commented May 23, 2021

넵 수고하셨습니다.

@be9904 be9904 changed the title Problem with require.js Problem with require May 24, 2021
@be9904
Copy link
Owner Author

be9904 commented May 25, 2021

문제
CORS(Cross Origin Resource Sharing) 오류: 브라우저는 script에서 온 http request를 제한함

이를 해결하기 위해서

  1. —disable-web-security(Chrome): 위험해서 하지 말라는 내용이 대부분이라 스킵
  2. 프록시 설정: 여러 글에서 공통으로 가능은 하지만 웬만하면 하지 말라해서 스킵
  3. Access-Control-Origin-Allow header 옵션을 Access-Control-Origin-Allow: *(전부 포함으로 변경): 이걸 하기 위해서 const express = require("express");를 이용하면 콘솔에서 되지만 웹에서는 안됨(알고보니 backend 전용 모듈이라 bundle.js로 만들어도 불가능)
  4. https.get을 통해 가져온 jsondata를 로컬 변수에 저장하여 script 및 html에 이용: https.get은 asynchronous function이라 global variable을 설정해도 https.get이 맨 나중에 실행되어 https.get 밖에서 console.log를 실행해봐도 global variable은 크롤링 되기 전의 값을 출력함. 따라서 불가능
  5. python을 통해 크롤링 후 dictionary형태의 데이터를 string으로 변환 후 내용을 data.txt라는 별도의 파일에 기록, 그 후 js를 통해 txt 파일의 내용을 추출: javascript는 local에 있는 파일의 접근성이 제한적이라 불가능

@ChanuYu ChanuYu closed this as completed May 25, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants