五大方法——解决同源策略的跨域CORS

方案一 jsonp

服务端

/*
比如这是要跨越请求的接口
那么接口要返回text/javascript格式的数据
并且用回调函数的名字封装一个返回值,通过send方式返回,拼接的字符串类似于:callback(a,b,c,...)
*/
app.get('/cors', function(req, res, next) {
    // 获取回调函数的名称,等会封装返回值要用到
    var _callback = req.query.jsoncallback;
    // 
    var param1 = [['aa','bb'],['cc','dd'],['ee']]
    var param2 = {'name':'juck', 'password':'admin'}
    // 返回值类型为javascript,否则会出现警告
    res.type('text/javascript');
    // 封装返回值
    res.send(_callback + '(' + JSON.stringify(param1) + ',' + JSON.stringify(param2) + ')');
});

1. javascript使用jsonp:


<html>
<head>
<meta charset="utf-8">
<title>JSONP 实例title>
head>
<body>
    <div id="divCustomers">div>
    <script type="text/javascript">
function callbackFunction(result, methodName)
        {
            var html = '
    '; for(var i = 0; i < result.length; i++) { html += '
  • ' + result[i] + '
  • '
    ; } html += '
'
; console.log(result) console.log(methodName) document.getElementById('divCustomers').innerHTML = html; }
script> <script type="text/javascript" src="http://localhost/cors?jsoncallback=callbackFunction">script> body> html>

2. jQuery使用jsonp


<html>
<head>
    <meta charset="utf-8">
    <title>JSONP 实例title>
    <script src="http://cdn.static.runoob.com/libs/jquery/1.8.3/jquery.js">script>    
head>
<body>
<div id="divCustomers">div>
<script>
$.getJSON("http://localhost/cors?jsoncallback=?", function(data) {
    var html = '
    '; for(var i = 0; i < data.length; i++){ html += '
  • ' + data[i] + '
  • '
    ; } html += '
'
; $('#divCustomers').html(html); });
script> body> html>

3. ajax的jsonp


<html>
<head>
    <meta charset="utf-8">
    <title>JSONP 实例title>
    <script src="http://cdn.static.runoob.com/libs/jquery/1.8.3/jquery.js">script>    
head>
<body>
<div id="divCustomers">div>
<script>
$.ajax({
    url:"http://localhost/cors",
    type:'get',
    dataType:'jsonp',
    jsonp:'jsoncallback',
    jsonpCallback: 'callback_success',
    success: function(data){
        var html = '
    '; for(var i = 0; i < data.length; i++){ html += '
  • ' + data[i] + '
  • '
    ; } html += '
'
; $('#divCustomers').html(html); } })
script> body> html>

使用该方式的缺点:请求方式只能是get请求

方案二 jQuery的jsonp插件访问(服务端同上)


<html>
<head>
    <meta charset="utf-8">
    <title>JSONP 实例title>
    <script src="http://cdn.static.runoob.com/libs/jquery/1.8.3/jquery.js">script>    
    
    <script src="https://github.s3.amazonaws.com/downloads/jaubourg/jquery-jsonp/jquery.jsonp-2.4.0.min.js?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAISTNZFOVBIJMK3TQ%2F20190417%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20190417T072705Z&X-Amz-Expires=300&X-Amz-SignedHeaders=host&X-Amz-Signature=a05ddb572f346629bfb9f67fcd6d9d7c7a32d661954552fa980ce20d08833501">script>
head>
<body>
<div id="divCustomers">div>
<script>
$.jsonp({
    url:"http://localhost/cors",
    callbackParameter: 'jsoncallback',//名字可以自定义,但是要跟后端获取时一致
    callback: 'callback_success',
    success: function(data){
        var html = '
    '; for(var i = 0; i < data.length; i++){ html += '
  • ' + data[i] + '
  • '
    ; } html += '
'
; $('#divCustomers').html(html); }, error: function(xOptions, textStatus){ alert("服务器异常") window.console.log(xOptions); window.console.log(textStatus); } })
script> body> html>

使用该方式的特点:与方式一相比,请求方式不只局限于get请求,还可以是post请求,但从服务器从获取的数据依然是jsonp格式

方案三 使用CORS

在Node(Express框架)服务器的返回(响应)中设置信息:

app.use("*", function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*'); 
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With"); 
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); 
    if (req.method === 'OPTIONS') {
        res.send(200) 
    } else {
        next() 
    } 
});
// 不使用上面的代码而是使用cors插件也可以(用npm下载cors包,设置为express的中间件)

若后端使用的java,则添加如下代码(也可以在springmvc中配置拦截器):

// 设置:
Access-Control-Allow-Origin头,处理Session问题
response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("P3P", "CP=CAO PSA OUR");
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
    response.addHeader("Access-Control-Allow-Methods", "POST,GET,TRACE,OPTIONS");
    response.addHeader("Access-Control-Allow-Headers", "Content-Type,Origin,Accept");
    response.addHeader("Access-Control-Max-Age", "120");
}

使用该方式的特点:与前两种方式相比,前端代码和未处理跨域前一样,即普通的ajax请求,但服务器代码添加了一段解决跨域的代码

方案四 使用浏览器插件

火狐拓展商店下搜索:CROS anywhere

谷歌拓展商店下搜索:CORS

方案五 使用代理服务器

如nginx配置代理, vue-cli配置proxy, 等等
教程请看对应的官方资源或百度。

你可能感兴趣的:(跨域,CORS,同源策略)