VUE cross-domain, commonly used methods to solve cross-domain

When we encounter Access-Control-Allow-Origin in the request background interface , it means cross-domain.

Cross-domain is caused by the same-origin policy of the browser. The same-origin policy (Same origin policy) is a convention, which is the core and most basic security function of the browser. The same-origin refers to: the domain name, protocol, and port are the same

Common methods to solve cross-domain:

1. Proxy is commonly used in VUE2.0 to solve cross-domain problems

1. Set the following code snippet in vue.config.js

module.exports = {
  dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: { // 配置跨域
    '/api':{
        target:`http://www.baidu.com`, //请求后台接口
        changeOrigin:true, // 允许跨域
        pathRewrite:{
            '^/api' : '' // 重写请求
        }
    }
  },
}

 2. When creating an axioss instance, set the baseUrl to '/api'

const http = axios.create({
  timeout: 1000 * 1000000,
  withCredentials: true,
  BASE_URL: '/api'
  headers: {
     'Content-Type': 'application/json; charset=utf-8'
   }
})

2. JSONP solves cross-domain

Jsonp (JSON with Padding) is a "use mode" of json, which allows web pages to obtain data from other domain names (websites), that is, to read data across domains.

<!DOCTYPE html>
       <html>
       <head>
           <meta charset="utf-8">
       </head>
       <body>
       <div id="textID"></div>
       <script type="text/javascript">
           function text_jsonp(req){
               // 创建script的标签
               var script = document.createElement('script');
               // 拼接 url
               var url = req.url + '?callback=' + req.callback.name;
               // 赋值url
               script.src = url;
               // 放入头部
               document.getElementsByTagName('head')[0].appendChild(script);
           }
       </script>
       </body>
       </html>

 3. CORS is cross-origin resource sharing (Cross-Origin Resource Sharing), which uses ajax to request resources across domains, supports modern browsers, and IE supports more than 10

In a CORS request, the header information contains the following three fields:

Access-Control-Allow-Origin: This field is required. Its value is either Originthe value of the field at the time of the request, or one *, indicating that it accepts requests from any domain name,

Access-Control-Allow-Credentials: Optional, the value is a Boolean value, indicating whether to allow sending cookies. By default, cookies are not included in CORS requests. If it is set true, it means that the server expressly allows that Cookie can be included in the request and sent to the server together. This value can only be set totrue。如果要发送Cookie,Access-Control-Allow-Origin必须设置为必须指定明确的、与请求网页一致的域名

Access-Control-Expose-Headers: Optional. When CORS requests, the method XMLHttpRequestof the object getResponseHeader()can only get 6 basic fields: Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma. If you want to get other fields, you must Access-Control-Expose-Headersspecify in it

For a detailed explanation, please refer to Ruan Dashen's article, attached to the portal: CORS Detailed Explanation

Fourth, iframe realizes cross-domain

iframe(src){
            //数组
            if(Array.isArray(src)){
                this.docs.visible = true;
            }else{
                this.docs.visible = false;
                
            }
            this.link  = src
            if(this.docs.visible == false){
                if(this.$refs['ruleIframe'] && this.$refs['ruleIframe'].querySelector('iframe')){
                    this.$refs['ruleIframe'].querySelector('iframe').remove()    //删除自身
                }
                var iframe = document.createElement('iframe');
                iframe.width = '100%';
                iframe.height = '100%';
                iframe.setAttribute('frameborder','0')
                iframe.src = src;                
                this.append(iframe)
            }
            
        },
        //创建元素 防止  获取不到 ruleIframe 递归
        append(iframe){
            if(this.$refs['ruleIframe']){
                this.$refs['ruleIframe'].appendChild(iframe);
                return
            }
            setTimeout(()=>{
                this.append(iframe);
            },500)    
        },

Thank you for reading~

Hope to help everyone

Guess you like

Origin blog.csdn.net/codingLeader/article/details/122712670