2017-09-18 2 views
2

ionic serve 명령을 실행하는 동안 오류가 발생했습니다. post 메서드를 사용하여 api를 호출하려고합니다.ionic 2 REST API : URL로드 실패

Failed to load http://abc.localhost/api/auth/login : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:8101 ' is therefore not allowed access.

가 어떻게이를 극복 할 수

나는 오류가있어?

에게 나는 다음 행동 API 모듈에서 YII2 프레임 워크의 API를의를 작성한

:

public function behaviors() { 
    $behaviors = parent::behaviors(); 
    $behaviors['contentNegotiator'] = [ 
     'class' => 'yii\filters\ContentNegotiator', 
     'formats' => [ 
      'text/html' => Response::FORMAT_JSON, 
      'application/json' => Response::FORMAT_JSON, 
      'application/xml' => Response::FORMAT_XML, 
     ], 
    ]; 
    $behaviors['corsFilter'] = [ 
     'class' => \yii\filters\Cors::className(), 
     'cors' => [ 
      'Origin' => ['*'], 
      'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'], 
      'Access-Control-Request-Headers' => ['*'], 
      'Access-Control-Allow-Credentials' => true, 
      'Access-Control-Max-Age' => 86400, 
      'Access-Control-Allow-Origin' => ['*', 'http://abc.localhost/*', 'http://localhost:8101/*'] 
     ], 
    ]; 
    return $behaviors; } 

그리고 내 ionic2 코르도바 API 호출 스크립트가 : 심지어

loading.present(); 
console.log(this.singleton.apiGuestToken); 
let headers = new Headers(); 
headers.append("Accept", 'application/json'); 
headers.append('Content-Type', 'application/json'); 
headers.append('Authorization', this.singleton.apiGuestToken); 
headers.append('withCredentials', 'true'); 
headers.append('Access-Control-Allow-Origin', 'http://abc.localhost'); 

let options = new RequestOptions({ headers: headers }); 
console.log(options); 
let paramsData = { 'userType': userType, 'email': this.email, 'password': this.password }; 
console.log(paramsData); 
this.http.post('http://abc.localhost/api/auth/login', paramsData, options) 
    .map(res => res.json()) //this.singleton.apiUrl + 
    .subscribe(data => { 
    let resultData = JSON.parse(data['_body']); 
    console.log(resultData); 
     }, error => { 
    console.log(error);// Error getting the data 
    loading.dismiss(); 
    }); 

, 나는 볼 수 없습니다 사후 매개 변수 및 인증을 제공합니다. 미리 감사드립니다.

답변

1

개발하는 동안 CORS plugin for Google Chrome을 사용할 수 있습니다.

CORS is only an issue when we are running or testing our app when running ionic serve or ionic run -l .

There are two ways to solve the issue: The first, and easier, solution is to just allow all origins from your API endpoint. However, we can’t always control the endpoint we are accessing. What we need, then, is a request that does not specify an origin . - Handling CORS issues in Ionic

+0

토미 슬라브에 감사드립니다! 나는'ionic cordova run -l' 명령을 실행하여 장치에서 응용 프로그램을 실행하려고했습니다. 그것은 나를 보여줍니다 ** http : //abc.localhost/api/auth/login을로드하지 못했습니다 : 프리 플라이트 요청에 대한 응답이 액세스 제어 검사를 통과하지 못했습니다 : 요청한 페이지에 'Access-Control-Allow-Origin'헤더가 없습니다 의지. 따라서 'http : // localhost : 8100'은 액세스가 허용되지 않습니다. ** –

2

나는이 문제에 대한 많은 궁금하지만 난 지금

{ 
    "name": "MyApp", 
    "app_id": "", 
    "integrations": { 
    "cordova": {} 
    }, 
    "proxies": [ 
    { 
     "path": "/api", 
     "proxyUrl" : "http://abc.localhost/api/" 
    } 
    ], 
    "type": "ionic-angular" 
} 

내가로부터 나머지 API를 호출하고 ionic.confog.json에 코드 아래에 추가 here

간단한 해결책을 발견 POST 메서드를 사용하여 http://abc.localhost/api/auth/login 액션 이전

내가 사용하려고했던 :

this.http.post('http://abc.localhost/api/auth/login', paramsData, options) 
.subscribe(data => { 
    let resultData = JSON.parse(data['_body']); 
    console.log(resultData); 
     }, error => { 
    console.log(error);// Error getting the data 
    loading.dismiss(); 
    }); 

을하지만이 같은 API를 호출 할 필요했다 :

this.http.post('api/auth/login', paramsData, options) 
.subscribe(data => { 
    let resultData = JSON.parse(data['_body']); 
    console.log(resultData); 
     }, error => { 
    console.log(error);// Error getting the data 
    loading.dismiss(); 
    }); 

프록시 경로가 이미 설정되었을 때 차이가 나머지 API의 URL을 호출 참조 설정 파일. 나를 위해 작동합니다.