原生ajax 如何解决cors跨域问题

用原生ajax请求进行cors跨域问题 他会显示origin不允许 没有后端支持的情况下怎么写ajax请求头啊。因为可能用到微信小程序,就最好不用第三方库。救救孩子 下面使用promise封装的ajax 要怎么改请求头
function ajax(options) {
  //这个options时传入给ajax的配置参数
  return new Promise((resolve, reject) => {
    //返回一个promise对象 resolve成功是的处理,reject失败时的处理
    if (!options.url) { // 需要请求的路径
      console.log("请确认你的url路径");
      return;
    }
    let method = options.method || "GET"; //请求方式如果没有就默认为get
    let async = options.async || true; //ajax是否异步请求默认位true
    let xhr = new XMLHttpRequest();
    if (method === "GET") {
      xhr.open(method, options.url + "?" + Math.random(), async); //防止缓存
      xhr.send(null);
    } else if (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 => {});
}

#笔试题目#
全部评论
cors 跨域时,浏览器会自动加请求头的(或者发 OPTION 请求),所以跟前端没关系,需要后端处理
点赞 回复
分享
发布于 2021-03-27 22:53
cors本身就是后端配置好了你直接请求的 没有后端支持就只能用别的办法了呀
点赞 回复
分享
发布于 2021-03-31 00:39
滴滴
校招火热招聘中
官网直投
fetch设置mode no-cors
点赞 回复
分享
发布于 2021-03-31 17:11

相关推荐

点赞 2 评论
分享
牛客网
牛客企业服务