JavaScript浏览器的跨域问题解决方案

为什么要跨域

同源策略

浏览器的同源策略:是浏览器的一个安全功能,不同源的网页脚本在没有明确授权的情况下,不能读写对方的资源,也就是会阻止一个域的javascript脚本和另外一个域的内容进行交互

同源

同源指的是(“协议+域名+端口”)三者相同

跨域问题

解释:使用AJAX技术(XML HttpRequest对象),从一个网页去请求另一个网页的资源时,违反了浏览器的同源策略,限制引起的安全问题。

解决跨域的思路:

  • 根源上解决,不使用ajax技术
  • 授权跨域资源共享

解决跨域

(列举三个最常用的CORS、JSONP和代理服务器nginx)

CORS

CORS 是跨域资源分享(Cross-Origin Resource Sharing)的缩写。它是 W3C 标准,属于跨源 AJAX 请求的根本解决方法。

  • 普通跨域请求只需要服务端设置 Access-Control-Allow-Origin
  • 带cookie的跨域请求前后端都需要设置

【前端设置】根据xhr.withCredentials字段判断是否带有cookie

1.原生ajax写法

var xhr = new XMLHttpRequest(); // IE8/9需用window.XDomainRequest兼容
// 前端设置是否带cookie
xhr.withCredentials = true;
xhr.open('post', 'http://www.domain2.com:8080/login', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('user=admin');
xhr.onreadystatechange = function() {
 if (xhr.readyState == 4 && xhr.status == 200) {
 alert(xhr.responseText);
 }
};

2.jQuery ajax

$.ajax({
 url: 'http://www.test.com:8080/login',
 type: 'get',
 data: {},
 xhrFields: {
 withCredentials: true // 前端设置是否带cookie
 },
 crossDomain: true, // 会让请求头中包含跨域的额外信息,但不会含cookie
});

3.vue-resource

Vue.http.options.credentials = true

4.axios

axios.defaults.withCredentials = true

5.fetch()方法实现

<script>
 fetch("http://127.0.0.1:35911", // url地址
 {method: "GET"}) // 用服务器允许的方法请求
 .then{ resonse => response.json{} } // 
 .then{ data => console.log{data.like} };
 </script>

fetch方法的node.js后台设置

cosnt express = require{'express '};
const cors = require{'cors'};
const app = express{};
app.use(
 cors ({
 origin:"*", // 允许所有源进行访问
 methods:['GET','POST'] // 定义可以访问的方法
 })
);
app.get('/',{request,response} =>{
 response.json(
 {"name:"hello","wrold"}
 );
});
app.listen(35911);

【服务端设置】

服务器端对于CORS的支持,主要是通过设置Access-Control-Allow-Origin来进行的。如果浏览器检测到相应的设置,就可以允许Ajax进行跨域的访问。

1.Nodejs后台

var http = require('http');
var server = http.createServer();
var qs = require('querystring');
server.on('request', function(req, res) {
 var postData = '';
 // 数据块接收中
 req.addListener('data', function(chunk) {
 postData += chunk;
 });
 // 数据接收完毕
 req.addListener('end', function() {
 postData = qs.parse(postData);
 // 跨域后台设置
 res.writeHead(200, {
 'Access-Control-Allow-Credentials': 'true', // 后端允许发送Cookie
 'Access-Control-Allow-Origin': 'http://www.domain1.com', // 允许访问的域(协议+域名+端口)
 /* 
 * 此处设置的cookie还是domain2的而非domain1,因为后端也不能跨域写cookie(nginx反向代理可以实现),
 * 但只要domain2中写入一次cookie认证,后面的跨域接口都能从domain2中获取cookie,从而实现所有的接口都能跨域访问
 */
 'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly' // HttpOnly的作用是让js无法读取cookie
 });
 res.write(JSON.stringify(postData));
 res.end();
 });
});
server.listen('8080');
console.log('Server is running at port 8080...');

2.PHP后台

<?php
 header("Access-Control-Allow-Origin:*");

JSONP技术原理

JSONP 是服务器与客户端跨源通信的常用方法。最大特点就是简单适用,兼容性好(兼容低版本IE),缺点是只支持get请求,不支持post请求。

核心思想:网页通过添加一个<script>元素,向服务器请求 JSON 数据,服务器收到请求后,将数据放在一个指定名字的回调函数的参数位置传回来。

1.原生实现

<script src="http://test.com/data.php?callback=dosomething"></script>
// 向服务器test.com发出请求,该请求的查询字符串有一个callback参数,用来指定回调函数的名字
// 处理服务器返回回调函数的数据
<script type="text/javascript">
 function dosomething(res){
 // 处理获得的数据
 console.log(res.data)
 }
</script>

2.Query ajax

$.ajax({
 // 请求域名
 url:'http://10.10.0.101:8899/login',
 // 请求方式
 type:'GET',
 // 数据类型选择 jsonp
 dataType:'jsonp',
 // 回调方法名
 jsonpCallback:'callback',
});
// 回调方法
function callback(response) {
console.log(response);
}

3.Vue.js

this.$http.jsonp('http://www.domain2.com:8080/login', {
 params: {},
 jsonp: 'handleCallback'
}).then((res) => {
 console.log(res); 
})

代理服务器nginx

跨域限制是浏览器的同源策略导致的,使用 nginx 当做服务器访问别的服务的 HTTP 接口是不需要执行 JS 脚本就不存在同源策略限制的,所以可以利用 Nginx 创建一个代理服务器,这个代理服务器的域名跟浏览器要访问的域名一致,然后通过这个代理服务器修改 cookie 中的域名为要访问的 HTTP接口的域名,通过反向代理实现跨域。

Nginx 的配置信息:

server {
    # 代理服务器的端口
    listen 88;
    # 代理服务器的域名
    server_name http://127.0.0.1;
    location / {
        # 反向代理服务器的域名+端口
        proxy_pass http://127.0.0.2:89;
        # 修改cookie里域名
        proxy_cookie_domain http://127.0.0.2 http://127.0.0.1;
        index index.html index.htm;
        # 设置当前代理服务器允许浏览器跨域
        add_header Access-Control-Allow-Origin http://127.0.0.1;
        # 设置当前代理服务器允许浏览器发送 cookie
        add_header Access-Control-Allow-Credentials true;
    }
}

前端代码:

var xhr = new XMLHttpRequest();
// 设置浏览器允许发送 cookie
xhr.withCredentials = true;
// 访问 nginx 代理服务器
xhr.open('get', 'http://127.0.0.1:88', true);
xhr.send();
作者:一杆老狙原文地址:https://blog.csdn.net/AKindofo/article/details/126584016

%s 个评论

要回复文章请先登录注册