Ionic2 proxyUrl无法在设备上运行

时间:2017-02-22 11:30:31

标签: android ios ionic-framework

在设备上运行应用时,它无法获取api url 它不会获取网址

我使用了以下编码

{
  "v2": true,
  "typescript": true,
  "proxies": [
    {
      "path": "/api",
      "proxyUrl": 'api url here'
    }
  ]
}

请提出任何建议

1 个答案:

答案 0 :(得分:2)

代理服务用于在浏览器中进行测试,以避免在使用外部API时出现No 'Access-Control-Allow-Origin' header is present on the requested resource错误。但这不是设备上的问题,因此不需要这种代理服务。因此,在设备上使用直接调用API网址而不是调用http://localhost:8100

如果要在设备和浏览器上进行测试,只需检查Cordova是否可用(以及您在设备上),然后定义要使用的URL。像这样:

import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import {Platform} from 'ionic-angular';
import 'rxjs/add/operator/toPromise';
import ...

@Injectable()
export class AccessService {
    private headers = new Headers({'Content-Type': 'application/json'});
    private apiUrl = '/v1/';

    constructor(private http: Http,
                public platform: Platform) {

        if (this.platform.is('cordova')) {                // <<< is Cordova available?
            this.apiUrl = 'https://api.instagram.com/v1/';
        }
    }

    login(username: string, password: string): Promise<string> {
        let postParams = {
            username: username,
            password: password
        };

        return this.http
            .post(this.apiUrl + 'login', postParams, this.headers)
            .toPromise()
            .then(response => response.json().devicetoken as string)
            .catch(this.handleError);
        }
    }

    ...
}
相关问题