JavaScript -AJAX/FETCH GET/POST及跨域方法

  • xhr 原生方法请求
var apiURL = 'https://api.github.com/repos/vuejs/vue/commits?per_page=3&sha=';
var currentBranch='master';
var commits= null;
function fetchData() {
    var xhr = new XMLHttpRequest()
    var self = this
    xhr.open('GET', apiURL + self.currentBranch)
    xhr.onload = function () {
        self.commits = JSON.parse(xhr.responseText)
        console.log(self.commits[0].html_url)
    }
    xhr.send()
}

function fetchDataPost(){ 
       // unload 时尽量使用同步 AJAX 请求
       xhr("POST",{ 
            url: location.href, 
            sync: true, 
            handleAs: "text", 
            content:{ 
                param1:1 
            }, 
            load:function(result){ 
                 console.log(result); 
            } 
       }); 
  }; 
  • window fetch 方法
  async function Fetch({url, data, method, config}) {
    method = method.toUpperCase();
    //window fetch方法
    if (window.fetch) {
      let requestConfig = {
        credentials: 'include',
        method: method,
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        mode: "cors",
        cache: "force-cache"
      };

      function assignConfig(targetConfig, sourceConfig) {
        if (sourceConfig) {
          Object.keys(sourceConfig).forEach(key => {
            if (sourceConfig[key]) {
              if (typeof sourceConfig[key] !== "object") {
                if (sourceConfig[key]) Object.assign(targetConfig, sourceConfig)
              } else {
                assignConfig(targetConfig[key], sourceConfig[key])
              }
            }
          })
        }
      }

      assignConfig(requestConfig, config);
      if (method === 'POST') {
        Object.defineProperty(requestConfig, 'body', {
          value: JSON.stringify(data)
        })
      }
      try {
        var response = await fetch(url, requestConfig);
        var responseJson = await response.json();
      } catch (error) {
        throw new Error(error)
      }
      return responseJson
    } else {
      let requestObj;
      if (window.XMLHttpRequest) {
        requestObj = new XMLHttpRequest();
      } else {
        requestObj = new ActiveXObject;
      }
      let sendData = '';
      if (method === 'POST') {
        sendData = JSON.stringify(data);
      }
      requestObj.open(method, url, true);
      if (config.headers) Object.keys(config.headers).forEach(key => {
        if (config.headers[key]) requestObj.setRequestHeader(key, config.headers[key])
      });
      requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      requestObj.send(sendData);
      requestObj.onreadystatechange = () => {
        if (requestObj.readyState === 4) {
          if (requestObj.status === 200) {
            let obj = requestObj.response;
            if (typeof obj !== 'object') {
              obj = JSON.parse(obj);
            }
            return obj
          } else {
            throw new Error(requestObj)
          }
        }
      }
    }
  }

  var baseUrl = "http://localhost:5000/api/";
  var loginUrl = "authentication/Login";
  var config = {
    headers: {
      Authorization: "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
    }
  };
  Fetch({
    url: baseUrl + loginUrl,
    method: "post",
    data: {"Name": "wwmin", "password": "1"},
    config
  }).then(res => console.log(res));
  • 关于跨域
//1.同源请求
$("#submit").click(function(){
  var data={
    name:$("name").val(),
    id:$("#id").val();
  };
  $.ajax({
    type:"POST",
    data:data,
    url:"http://localhost:3000/ajax/deal",
    dataType:"json",
    cache:false,
    timeout:5000,
    success:function(data){
      console.log(data);
    },
    error:function(jqXHR,textStatus,errorThrown){
      console.log("error"+textStatus+" "+errorThrown);
    }
  });
});

//node 服务器端3000 对应的处理函数为:
pp.post('/ajax/deal',function(req,res){
  console.log("server accept:",req.body.name,req.body.id)
  var data={
    name:req.body.name+'-server 3000 process',
    id:req.body.id+'-server 3000 process'
  };
  res.send(data);
  res.end();
})
  • 利用JSONP实现跨域调用
//JSONP 是 JSON 的一种使用模式,可以解决主流浏览器的跨域数据访问问题。
//  其原理是根据 XmlHttpRequest 对象受到同源策略的影响,而 
function jsonpCallback(data){
  console.log("jsonpCallback:"+data.name)
}
//服务器 3000请求页面还包含一个 script 标签:

//服务器 3001上对应的处理函数:
app.get('/jsonServerResponse', function(req, res) {
    var cb = req.query.jsonp
    console.log(cb)
    var data = 'var data = {' + 'name: $("#name").val() + " - server 3001 jsonp process",' + 'id: $("#id").val() + " - server 3001 jsonp process"' + '};'
    var debug = 'console.log(data);'
    var callback = '$("#submit").click(function() {' + data + cb + '(data);' + debug + '});'
    res.send(callback)
    res.end()
})
  • 使用 CORS(跨域资源共享) 实现跨域调用
//CORS 的实现
//服务器 3000 上的请求页面 JavaScript 不变 (参考上面的同域请求)
//服务器 3001上对应的处理函数:
app.post('/cors', function(req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    var data = {
        name: req.body.name + ' - server 3001 cors process',
        id: req.body.id + ' - server 3001 cors process'
    }
    console.log(data)
    res.send(data)
    res.end()
})
// CORS 中属性的分析
//1.Access-Control-Allow-Origin
The origin parameter specifies a URI that may access the resource. The browser must enforce this. For requests without credentials, the server may specify “*” as a wildcard, thereby allowing any origin to access the resource.
//2.Access-Control-Allow-Methods
Specifies the method or methods allowed when accessing the resource. This is used in response to a preflight request. The conditions under which a request is preflighted are discussed above.
//3.Access-Control-Allow-Headers
Used in response to a preflight request to indicate which HTTP headers can be used when making the actual request.

// CORS 与 JSONP 的对比
//1.CORS 除了 GET 方法外,也支持其它的 HTTP 请求方法如 POST、 PUT 等。
//2.CORS 可以使用 XmlHttpRequest 进行传输,所以它的错误处理方式比 JSONP 好。
//3.JSONP 可以在不支持 CORS 的老旧浏览器上运作。

//一些其它的跨域调用方式
//1.window.name
//2.window.postMessage()
//参考:https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

你可能感兴趣的:(JavaScript -AJAX/FETCH GET/POST及跨域方法)