我想在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
});
}
像这样使用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());
希望它有效。
尝试在文件顶部的Rest Api文件中添加Allow-Control-Allow-Origin