【问题标题】:ionic 2 No 'Access-Control-Allow-Origin' headerionic 2 没有“访问控制允许来源”标头
【发布时间】:2017-12-27 01:49:42
【问题描述】:

我想在restfull api上发布数据,但我接受(XMLHttpRequest无法加载https://deneme.com/api/v1.0/users/login/。对预检请求的响应未通过访问控制检查:请求中不存在“Access-Control-Allow-Origin”标头资源。因此,不允许访问源“http://localhost:8100”。)错误。

我使用 chrome 插件 (Allow-Control-Allow-Origin: *) 解决了这个问题,名称是交叉的。但我的代码不适用于 android 设备。我如何用代码解决这个问题

我的代码;

kanallistele()
{

  var veri;

     this.kanallardiv=true;
    this.uyegirisdiv=false;
    this.kanallistelebtn = false;
    var headers = new Headers();
    headers.append('Accept', 'application/json');
    headers.append('Content-Type', 'application/json' );
    headers.append('Access-Control-Allow-Origin','*'); 
    //headers.append('Authorization' , 'Basic '+ btoa(tok));
    let options = new RequestOptions({ headers: headers });

    let postParams = {
    token: "381f13d7056-ce5fe474919",
    user_id: "71",
    }

    var veris="channel_name_";
    this.http.post("https://deneme.com/api/v1.0/channels/", postParams, options)
      .subscribe(data => {
        veri = data['_body'];
        console.log(veri);       
        veri= veri.slice(1, -1);
        veri = veri.replace(/\\/g, "");
        veri = JSON.parse(veri);
        for(var i = 0 ;;i++)
          {
              if(!veri.channel_list['channel_name_' + (i)])
                    break;   

              this.veriler.push({channelname: veri.channel_list['channel_name_' + (i)],channelid: veri.channel_list['channel_id_' + (i)]});              
          }
       }, error => {
        console.log(error);// Error getting the data
      });  
  }

【问题讨论】:

  • 此链接可能会有所帮助stackoverflow.com/questions/37599655/…
  • 试试let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });。删除所有其他标题。
  • 添加您的 config.xml 和您正在使用的插件列表。

标签: typescript ionic2 http-headers xmlhttprequest


【解决方案1】:

像这样使用 Header 参数:

let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.headers = {headers};
this.http.post(API_URL, JSON.stringify(userData), this.headers).map(res => 
res.json());

希望它有效。

【讨论】:

    【解决方案2】:

    尝试在文件顶部的 Restapi 文件中添加 Allow-Control-Allow-Origin

    【讨论】:

      猜你喜欢
      • 2018-04-12
      • 2016-01-02
      • 2017-07-24
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      • 2018-10-18
      • 2017-07-21
      相关资源
      最近更新 更多