본문으로 바로가기

1. JSONP 사용 

 

일반적인 ajax client

$.ajax({
    type: 'post',
    dataType: "jsonp",
    url: 'API URL',
    jsonpCallback: "myCallback",
    async: false, //동기: false, 비동기: ture
    data: {u_token:token},
    success: function (data) {
		//성공
    },
    complete : function(data) {
      	// 통신이 실패했어도 완료가 되었을 때 이 함수를 타게 된다.
    },
    error: function (request, status, error) {

    }

});

일반적인 server

myCallback({"키1":"값1", "키2":"값2", "키3":"값3"})

 

2. React client 측에서 proxy 설정

 

React의 package.json에 "proxy" : "" 추가

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.9.0",
    "react-dom": "^16.9.0",
    "react-scripts": "3.1.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy" : "서버 주소"
}

 

 

3. node.js server측에서 CORS 라이브러리 사용 

// CORS 설정
const cors = require('cors');

var whitelist = ['http://localhost:4000', 'http://localhost:4001']

var corsOptions = {

    origin: function(origin, callback){
        var isWhitelisted = whitelist.indexOf(origin) !== -1;
        callback(null, isWhitelisted);
        // callback expects two parameters: error and options
    },
    credentials:true

}

app.use(cors(corsOptions));

 

참조

https://daveceddia.com/access-control-allow-origin-cors-errors-in-react-express/

 

 

 

4. node.js 서버 측에 응답 헤더 추가

 

app.get('/api/test', function (req, res, next) {

    res.setHeader("Access-Control-Allow-Origin", 'http://localhost:4000');
    res.setHeader('Access-Control-Allow-Methods', 'POST,GET,OPTIONS,PUT,DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Accept');

    res.send('Hello World!');

});

 

 

웹 브라우저의 스크립트 엔진에서 preflight 요청 응답으로 Access-Control-Allow-Origin header에 “*" 값이 있으면 모든 도메인에서의 요청을 허용하는 것으로 판단



 

* PHP 시 해더 추가

header('Access-Control-Allow-Origin: *');
header('Access-Control-Max-Age: 86400');
header('Access-Control-Allow-Headers: x-requested-with');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Content-Type: text/html; charset=UTF-8');

 

 

 

참조 

infotake.tistory.com/88

 

[Javascript] 자바스크립트 Ajax 외부 통신 크로스 도메인 해결 - CORS

촌놈입니다! 웹 개발들 많이 하시죠? 제가 웹 개발을 처음 할때는 IE6 - 익스플로러6 이 대다수 사용하고 있었는데 지금은 대세가 Chrome으로 바뀌고 익스플로러도 Edge 까지 나왔으니 정말 많이 변��

infotake.tistory.com

 

'[ Web 관련 ] > node.js' 카테고리의 다른 글

node.js 설치 (centos7) + mysql 연결  (0) 2019.08.21