用原生ajax请求进行cors跨域问题他会显示origin不允许没有后端支持的情况下怎么写ajax请求头啊。因为可能用到微信小程序,就最好不用第三方库。救救孩子 下面使用promise封装的ajax 要怎么改请求头
functionajax(options){
//这个options时传入给ajax的配置参数
returnnewPromise((resolve,reject)=>{
//返回一个promise对象resolve成功是的处理,reject失败时的处理
if(!options.url){//需要请求的路径
console.log("请确认你的url路径");
return;
}
letmethod=options.method||"GET";//请求方式如果没有就默认为get
letasync=options.async||true;//ajax是否异步请求默认位true
letxhr=newXMLHttpRequest();
if(method==="GET"){
xhr.open(method,options.url+"?"+Math.random(),async);//防止缓存
xhr.send(null);
}elseif(method==="POST"){
xhr.open(method,options.url,async);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(options.data);
}
//xhr.responseType=options.type||"";
xhr.onreadystatechange=()=>{
if(xhr.responseText){
//有数据说明相应成功
resolve(xhr.responseText);
}
};
xhr.onerror=err=>{
reject(err);
};
}).catch(e=>{});
}