< a href="https://github.com/%E5%B0%8F%E7%9A%AE%E6%B5%A9"> Fork me on GitHub

vue之同源策略

<!doctype html>

vue之同源策略

vue之同源策略

vue请求方式(axios)

axios.get('资源服务器',{
          params:{   //get参数   如https://www.badu.comid=(参数)
                id:参数
          }
          }).then(function(response){   //response是请求成功后返回的数据
        console.log(response)      
          }).catch(function(error){    //error是请求失败后的返回数据
        console.log(error)  //无法显示服务端的错误,只会接收服务端的错误
          })

同源策略报错

Access to XMLHttpRequest at 'http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.catalogSug&query=%E6%88%91%E7%9A%84%E4%B8%AD%E5%9B%BD%E5%BF%83' from origin 'http://localhost:63342' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

关键词:Access-Control-Allow-Origin

只要出现这个错误,就是访问受限。出现策略的拦截问题

同源策略报错解决方式

同源策略:是浏览器的一种保护用户数据的一种安全机制,浏览器会限制ajax不能跨域访问其他源的数据地址。

同源:判断两个同心地址之间,是否协议,域名[ip],端口一致

同源策略报错原因也是协议,域名和端口有其一不一致的问题

解决方式

ajax跨域(跨源)方案之CORS

CORS是一个W3C标准,全称是"跨域资源共享",他允许浏览器向跨源的后端服务器发出ajax请求,从而克服ajax只能同源使用的限制

实现CORS主要依靠后端服务器中相应数据中在响应头信息返回信息的

CORS在django中的使用

#django视图

def post(request):
response = new HttpResponse()
response.set_header("Access-Control-Allow-Origin","http://localhost:63342")
return response;

//在响应行信息里面设置一下内容:
Access-Control-Allow-Origin:ajax所在的域名地址

Access-Control-Allow-Origin:www.oldboy.cn  #

vue中设置

待更新

jsonp

利用跨域标签来解决的

jsonp可以实现跨域,但是并非ajax技术

核心是利用script标签

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
        <input type="text" id="content">
        <button onclick="get_data()">翻译</button>
        <p id="p1"></p>
    </div>
    <script>
    // jsonp本身并不是ajax
    // jsonp利用的是script标签的本身特性
    // 实现json需要客户端和服务端配合
    function hello(data){
        // 自定义业务
        //当点击之后,发送请求服务器,js会自动调用这个函数(函数名必须和请求连接中的callback参数一致,传入的参数就是请求响应的参数)
        var p1 = document.getElementById("p1");
        p1.innerHTML = data.data;
        console.log(data);
    }
function get_data(){
    // 通过js的DOM操作创建一个script标签
    var script = document.createElement(&quot;script&quot;);
    var content = document.getElementById(&quot;content&quot;);
    // 给script标签设置src属性为服务端的js脚本
    script.src = &quot;https://api.asilu.com/fanyi/?callback=hello&amp;q=&quot;+content.value;
    console.log(script);
    // 把新建的script标签追加到网页给浏览器识别
    //通过将处理好的script标签交给document的head处理,让浏览器识别
    document.head.append(script);
}

&lt;/script&gt;

</body>
</html>

服务端代理

posted @ 2020-02-14 19:38  赌徒!  阅读(1513)  评论(0编辑  收藏  举报