利用iframe解决跨域请求

用iframe解决跨域问题的关键在于利用window.name属性不会随页面跳转而丢失,在parent域名下内嵌iframe请求跨域接口,将请求回来的数据结果赋值给iframe的contentWindow.name。此时由于浏览器限制跨域访问iframe.contentWindow的属性,所以不能直接访问iframe的window.name属性。此时需要将iframe转为同一域名,然后在parent层就可以直接获取。


代码模拟实现,(前端代码,动态创建iframe,src设为请求的接口url)

e.g:页面所在域名:http://127.0.0.1:8863/test.html,
请求接口地址:http://localhost:3000/dataByIframe
两者端口号不同,直接请求,必然造成跨域

<script type="text/javascript">
		var boo = false;
		var iframe = document.createElement('iframe');
		var loadData = function() {
			if (boo) {
				var data = iframe.contentWindow.name; //获取window.name
				console.log(data);	// this is the response data!
				iframe.contentWindow.top.document.getElementById('result').innerText = data;
				boo = false;
				//拿到数据后,清除辅助的iframe 销毁数据   
				iframe.contentWindow.document.write('');
				iframe.contentWindow.close();
				document.body.removeChild(iframe);
				iframe = null;
			} else {
				boo = true;
				// 由于浏览器限制跨域访问iframe, 此处需跳转回parent所在域名,(任意页面均可)
				// 统一window下的页面跳转不会改变window.name的值,利用该特性,在调回父域名后,
				// 即可访问同源下iframe的window.name
				iframe.contentWindow.location = 'a.html'; // 设置的代理文件,iframe重新载入
			}
		};
		iframe.src = 'http://localhost:3000/dataByIframe';
		if (iframe.attachEvent) {
			iframe.attachEvent('onload', loadData);
		} else {
			iframe.onload = loadData;
		}
		iframe.style.display = "none";
		document.body.appendChild(iframe);
</script>

服务端代码示意(nodejs)

var express = require('express')
var app = express()

// 测试iframe解决跨域问题
app.get('/dataByIframe', (req, res) => {
  //接口返回的测试数据,前端将接收responseData
	let responseData = 'this is the response data!'
	const response = ''
	res.send(response);
})

将前端代码封装成函数,以便调用

function ajaxWithCrs(url, data){
		var urlAppendings = [];
		for (var param in data) {
			urlAppendings.push(param + '=' + data[param]);
		}
		var requestUrl = url + '?' + urlAppendings.join('&');
		return new Promise(function (resolve, reject){
			var boo = false;
			var iframe = document.createElement('iframe');
			var loadData = function() {
				if (boo) {
					var data = iframe.contentWindow.name; //获取window.name
					boo = false;
					iframe.contentWindow.document.write('');
					iframe.contentWindow.close();
					document.body.removeChild(iframe);
					iframe = null;
					resolve(data)
				} else {
					boo = true;
					iframe.contentWindow.location = 'a.html'; // 设置的代理文件,iframe重新载入
				}
			};
			iframe.src = requestUrl;
			if (iframe.attachEvent) {
				iframe.attachEvent('onload', loadData);
			} else {
				iframe.onload = loadData;
			}
			iframe.style.display = "none";
			document.body.appendChild(iframe);
		});
	}

调用示例:

ajaxWithCrs('http://localhost:3000/dataByIframe', {test: 1})
	.then(function(data){
		console.log('back data is:', data)
	})

你可能感兴趣的:(JavaScript,ajax跨域,iframe)