实现通过跨域获取数据的几种方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36146776/article/details/83825294

test.js  使用node test.js端口

const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {
  console.log("req:" + req.url);
  res.writeHead('200', {
    'Access-Control-Allow-Origin': '*'
  });
  res.end('123');
}).listen(1111);

 在浏览器中输入http://localhost:1111/中即可返回123

test.html

方法一、jsonp
有些请求是不受到跨域限制。例如:WebSocket,script、img、iframe、video、audio标签的src属性等
<script src="http://127.0.0.1:1111"></script>
如果返回时json格式的数据,可以这样
<script>
  var script = document.createElement('script');
  script.src = 'http://127.0.0.1:1111/?cb=myCallback';
  document.getElementsByTagName('head')[0].appendChild(script);

  function myCallback(res) {
    alert(JSON.stringify(res, null, 2));
  }
</script>

<script>
方法二、fetch
    fetch('http://127.0.0.1:1111', {
      method: 'get',
      headers: {}
    }).then(function (res) {
      return res.json();
    }).then(function (res) {
      console.log(res);
    }).catch(function(e) {
      console.log("error");
    })

方法三、原生js
let xhr = new XMLHttpRequest();
    xhr.open('GET','http://127.0.0.1:1111');
    xhr.send();
    xhr.onload=function () {
      console.log(xhr.response);
      console.log(xhr.responseText);
}
方法四、jquery(先导入jquery)
$.get('http://127.0.0.1:1111', res => {
      console.log(res);
    });
//或者
$.ajax({
      url:'http://127.0.0.1:1111',
      method:'get',
      success:function (res) {
        console.log(res);
      }
    })

方法五、使用代理(proxy)
</script>

方法五链接

猜你喜欢

转载自blog.csdn.net/sinat_36146776/article/details/83825294