자유게시판

제목 rest API 만드는 도중..
글쓴이 작성시각 2016/10/28 14:35:37
댓글 : 2 추천 : 0 스크랩 : 1 조회수 : 11669   RSS

https://github.com/chriskacerguis/codeigniter-restserver

위 깃헙 라이브러리를 활용해서 미리 api를 만들었습니다.

postman으로 get 잘되서 아 땡잡았다 했는데 post는 안되더라고요. 이유는 config.php 에 csrf_protection = true설정

때문이었어요 그래서

hook을 이용해서 껐어요. curl로 요청했는데 잘되길래 react로 프론트 만들고 있는데 jquery ajax로 요청했는데

안되더라고요 ㅠㅠ 한 만 하루를 꼬박 구글링 및 낑낑대면서 원인을 알았습니다. ajax시 cors (다른도메인에서 요청하는건가봐요.) 관련

이슈였는데, 헤더에 추가를 해줘야 했어요. 혹시 고생하실까봐 소스 남깁니다.

hook 소스.. (pre_system에서 호출..)

class _Api_common {
    function index () {
        if (isset($_SERVER['REQUEST_URI'])) {
            $req_uri = explode('/',$_SERVER['REQUEST_URI']);
            if ($req_uri[1] == API_URI) {
                get_config(array('csrf_protection' => false));
                header('Access-Control-Allow-Origin: *');
                header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
                header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
                $method = $_SERVER['REQUEST_METHOD'];
                if($method == "OPTIONS") {
                    die();
                }
            }
        }
    }
}

자바스크립트 소스..

import $ from 'jquery';
import * as constant from '../constant/constant';


class Ylib {

  apiUrl (seg) {
    let url = constant.apiUrl
    return url + seg
  }//end apiUrl

  apiAjax(method='get',seg='',data,suc,err) {
    let contentType ="application/x-www-form-urlencoded; charset=utf-8";
    //for IE8,IE9
    if (window.XDomainRequest) contentType = "text/plain";
    let setting = {
      crossDomain:true,
      url: this.apiUrl(seg),
      type : method,
      dataType : 'json',
      contentType:contentType,
      beforeSend : function(xhr){
        xhr.setRequestHeader("X-API-KEY", constant.apiKey);
      },
      success: function(data) {
        if ( suc !== undefined && typeof(suc) === "function" ) suc(data)
      },
      error: (jqXHR, textStatus, errorThrown) => {
        if ( err !== undefined && typeof(err) === "function" ) err(jqXHR, textStatus, errorThrown)
      }
    }
    if (data !== undefined) setting = {...setting, data:data}
    return $.ajax(setting);
  } //end apiAjax

} //end class
const ylib = new Ylib();
export default ylib;

참고만 하세요~~ ^^;

 다음글 ci4 보고 있는데 재미있네요. (16)
 이전글 파이어폭스서 中 치후360 자회사 인증서 차단 (1)

댓글

한대승(불의회상) / 2016/11/03 17:48:15 / 추천 0
@닉 팁 게시판으로 옮겨도 괜찮을까요?
/ 2016/11/04 10:26:55 / 추천 0
아 네 ^^