반응형
axios
fetch


써드파티 라이브러리로 설치가 필요
현대 브라우저에 빌트인이라 설치 필요 없음


XSRF 보호를 해준다.
별도 보호 없음


data 속성을 사용
body 속성을 사용


data는 object를 포함한다
body는 문자열화 되어있다


status가 200이고 statusText가 ‘OK’이면 성공이다
응답객체가 ok 속성을 포함하면 성공이다


자동으로 JSON데이터 형식으로 변환된다
.json()메서드를 사용해야 한다.


요청을 취소할 수 있고 타임아웃을 걸 수 있다.
해당 기능 존재 하지않음


HTTP 요청을 가로챌수 있음
기본적으로 제공하지 않음


download진행에 대해 기본적인 지원을 함
지원하지 않음


좀더 많은 브라우저에 지원됨
Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+이상에 지원

출처: https://inpa.tistory.com/entry/AXIOS-📚-설치-사용#axios란 [👨‍💻 Dev Scroll:티스토리]

반응형
반응형

범용적인 목적으로 js를 사용하기 위한 선결조건: 모듈화

  • CommonJS
    • 브라우저 이외의 곳에서 JS를 사용하기 위한 모듈 시스템
    • 노드에서 많이 사용됨
    • CommonJS의 Common은 js를 브라우저만이 아닌 일반적인 범용언어로 사용살 수 있게 하겠다는 것
    • 필요한 파일이 모두 로컬디스크게 있어 바로 불러쓸 수 있는 상황 즉 서버사이드에서는 CommonJS가 AMD방식보다 간결함
  • AMD(Asynchronous Module Definition)
    • ES6가 나오기 전에 많이 사용됨
    • 주요특징
      • 모듈(자바스크립트)의 비동기 로딩 (html에서 script태그를 통해서 관리하는게 아닌 js로 script태그를 append하여서 로딩함
      • 클로저를 통한 전역관리
      • CommonJS에 비해 사용법 간단
    • AMD방식을 사용하는 대표적인 오픈소스가 RequireJS
    • 필요한 파일을 네트워크를 통해 내려받아야 하는 브라우저와 같은 환경에서는 AMD가 CommonJS보다 더 유연한 방법을 제공
  • ES6(2015)
    • 브라우저(frontend)에서는 요즘 거의 이것 사용
    • 그대로 쓰기보다 webpack/rollup 같은 번들러를 통해서 많이 사용됨

 

참고자료

https://isa-dev.tistory.com/217?category=994397

https://d2.naver.com/helloworld/12864

반응형
반응형

http://13.125.140.150:8080/posts
http://ec2-13-125-140-150.ap-northeast-2.compute.amazonaws.com:8080/posts
node /home/ec2-user/my-json-server/node_modules/.bin/json-server --host 172.31.10.248 --watch db.json --port 8080
nohup node /home/ec2-user/my-json-server/node_modules/.bin/json-server --host 172.31.10.248 --watch db.json --port 8080 &
-> 잘안되서 pm2 설치
pm2 start npm start -> 안됨
pm2 start `npm start` 됨!!!!

반응형

'js > node, npm' 카테고리의 다른 글

npm  (0) 2022.07.21
반응형
return fetch(`${API_BASE_URL}/admin/terms/published-terms?type=${data}`, {
  method: 'POST',
  headers: getHeaders(),
})
  //.then(res => res.json())
  .then(body => {
    console.log('body', body);
    console.log('body json', body.json());//이게 없으면 크롬인스텍서 preview, response에서 안보임
    console.log('body body', body.body);
    if (body.status===200)
      alert('Successfully Published !');
    else
      alert('Some Error Occured !');
  })
  .catch(() => {});
반응형
반응형

Access to fetch at 'http://kic-qt2-ngfts.lge.com/fts/gftsDownload.lge?biz_code=CDP&func_code=PROGRAM_IMAGE&file_path=/cdp/program_image/test/skin/ncaa_back_fhd.jpg' 

from origin 'http://localhost:3000' 

has been blocked by CORS policy: 

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 

If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

반응형
반응형

그냥 이렇게 쓰면 됨, ``내부에 또 ``넣는 건 안되는듯

json.data[0].word
  ? `${json.data[0].word} (${json.data[0].reading})`
  : `${json.data[0].reading}`
반응형
반응형

frontend server build 확인방법

  • npm run build (빌드결과물 생성됨)
  • npm install -g serve (serve 설치)
  • serve -s build (bash에서 실행해야함, 윈도우 터미널에서는 동작안함, 완료되면 localhost:5000에서 확인가능)

빌드완료되면 다음위치에 다음과 같은 결과물이 떨어짐
File sizes after gzip: 485.41 KB
build\static\js\2.f302d4b6.chunk.js 62.8 KB (-50 B)
build\static\js\main.42c20a87.chunk.js 53.73 KB
build\static\js\3.60c20971.chunk.js 39.12 KB
build\static\js\5.3a36e225.chunk.js 6.39 KB
build\static\js\4.f1151a7d.chunk.js 1.16 KB
build\static\js\runtime~main.39277503.js 283 B
build\static\css\main.3655cd5e.chunk.css

jss1 - max-whith:520px고정문제로 인해 로그인 첫화면 사이즈 작아짐, 원인은?

"@babel/runtime-corejs3": {
    "version": "7.9.6",
    "resolved": "https://registry.npmjs.org/@babel/runtime-corejs3/-/runtime-corejs3-7.9.6.tgz",
    "integrity": "sha512-6toWAfaALQjt3KMZQc6fABqZwUDDuWzz+cAfPhqyEnzxvdWOAkjwPNxgF8xlmo7OWLsSjaKjsskpKHRLaMArOA==",
    "dev": true, --->  이게원인인듯 
    "requires": {
        "core-js-pure": "^3.0.0",
        "regenerator-runtime": "^0.13.4"
    },
    "dependencies": {
        "regenerator-runtime": {
            "version": "0.13.5",
            "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.5.tgz",
            "integrity": "sha512-ZS5w8CpKFinUzOwW3c83oPeVXoNsrLsaCoLtJvAClH135j/R77RuymhiSErhm2lKcwSCIpmvIWSbDkIfAqKQlA==",
            "dev": true --->  이게원인인듯 
        }
    }
},
반응형
반응형

mainpage = <Redirect to="/dashboard" />;

mainpage=<meta http-equiv="refresh" content="0; url=/signin"/>;

window.location.href = '/signin';

mainpage = <Route path="/" component={Signin} />; re-render OK, not refresh

history.push('/PROGRAM/programlist');re-render ?, not refresh

 

import { Route, Redirect } from 'react-router-dom';

반응형

'js' 카테고리의 다른 글

CORS(Cross-Origin Resource Sharing)  (0) 2022.06.10
react-scripts build  (0) 2020.12.17
ES6(2015) - import/export  (0) 2020.03.24
eslint, prettier  (0) 2020.03.18
javascript timezone  (0) 2020.03.15
반응형
  • export
    • default
      • function, class만 가능, 아니면 Parsing error: Only expressions, functions or classes are allowed as the `default` export.에러남
      • import시   import 그냥  from  이렇게 사용
    • named
      • import시 import {일케}  from이렇게 해야함
      • export A를 import {B}로 바꿔서 사용가능
      • import {A as B} 이렇게도 변경가능
      • import * as lib from 이렇게 해서  전체를 lib로 받고 lib.a로 사용가능

 

 

반응형

'js' 카테고리의 다른 글

react-scripts build  (0) 2020.12.17
page redirect 방법들  (0) 2020.04.12
eslint, prettier  (0) 2020.03.18
javascript timezone  (0) 2020.03.15
frontend setting in Windows  (0) 2020.01.13
반응형

vsCode에서 사용방법

  • prettier 규칙적용: F1 > Format Document
  • 저장시 자동적용: settings.json에 추가 - "editor.formatOnSave"true,
  • eslint: F1 > ESLint fix all auto-fixable Problems
  "singleQuote": true, //문자열 입력 시 쌍따옴표(") 대신 따옴표(') 사용
  "semi": true, //코드 끝에 항상 세미콜론 추가
  "useTabs": false,
  "tabWidth": 2,
  "trailingComma": "all", //객체, 배열 등의 마지막 항목에 콤마(,) 추가
  "printWidth": 500,
  "bracketSpacing": true //괄호 안에 데이터가 있을 때 공백 삽입
{
  "arrowParens": "always",
  "bracketSpacing": true,
  "endOfLine": "lf",
  "htmlWhitespaceSensitivity": "css",
  "insertPragma": false,
  "singleAttributePerLine": false,
  "bracketSameLine": false,
  "jsxBracketSameLine": false,
  "jsxSingleQuote": false,
  "printWidth": 500,
  "proseWrap": "preserve",
  "quoteProps": "as-needed",
  "requirePragma": false,
  "semi": true,
  "singleQuote": false,
  "tabWidth": 2,
  "trailingComma": "es5",
  "useTabs": false,
  "embeddedLanguageFormatting": "auto",
  "vueIndentScriptAndStyle": false,
  "filepath": "c:\\workspace\\csportalfront\\src\\views\\Setting&Management\\EvaluationSetting.js",
  "parser": "babel"
}

https://prettier.io/docs/en/options.html

 

Prettier · Opinionated Code Formatter

Opinionated Code Formatter

prettier.io

 

prettier eslint
  "singleQuote": true,  //문자열은 '로만사용    
  "semi": true, //코드는 ;로 끝남 semi: ['warn', 'always']  
  "useTabs": false, //탭 사용여부 indent: ['warn', 'tab'] ???  
  "tabWidth": 2, //탭 크기    
  "trailingComma": "all", // 객체 끝 부분에도 Comma 추가 'comma-dangle': ['warn', 'never']과 대치됨  
  "printWidth": 100  // 줄 당 max length    
    'space-before-function-paren': ['warn', 'always']  get( x, get ( o
    'react/jsx-indent': ['warn', 'tab'],  
    'linebreak-style': ['warn', 'unix']  
    'react/sort-prop-types': [
      'warn',
      {
        ignoreCase: true,
        requiredFirst: true,
      },
    ],
 
 알파벳순 정렬안되면 에러
       
       
       
반응형

'js' 카테고리의 다른 글

page redirect 방법들  (0) 2020.04.12
ES6(2015) - import/export  (0) 2020.03.24
javascript timezone  (0) 2020.03.15
frontend setting in Windows  (0) 2020.01.13
Promise, async, await...  (0) 2020.01.02

+ Recent posts