解决跨域的几种方式

  • Post author:
  • Post category:其他




1.document.domain

由于js同源策略的限制,脚本只能读取和所属文档来源相同的窗口和文档属性

对于有公共的上级域名,这些服务器上的页面之间的跨域访问可以通过document.domain来进行

默认document.domain存放的是载入文档的服务器的主机名,可以手动设置这个属性,不过只能设置成当前域名或者上级域名,并且必须要包含一个.号。

举例:


zy.ttdvideo.com

可以设置成ttdvideo.com不能设置成com



注意:这两个域名必须属于同一个基础域名!而且所用的协议,端口都要一致,否则无法利用document.domain进行跨域

参考:

https://blog.csdn.net/nlznlz/article/details/79506655



2.CROS

CORS是一个W3C标准,全称是”跨域资源共享”(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。只要服务器实现了CORS接口,就可以跨源通信。

springBoot框架CROS配置

package com.joyware.whistlecloud.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * 2019-5-21 15:13
 * 
 * @author guowei
 */
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurationSupport {

/*    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedHeaders("Authorization, Content-Type")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }
    */


    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}



CROS常见的header

表明允许” http:/haha.com “发起跨域请求



Access-Control-Allow-Origin:

http://haha.com

表明在3628800秒内,不需要再发送预检验请求,可以缓存该结果(上面的资料上我们知道CROS协议中,一个AJAX请求被分成了第一步的OPTION预检测请求和正式请求)



Access-Control-Max-Age: 3628800

表明它允许GET、PUT、DELETE的外域请求



Access-Control-Allow-methods: GET, PUT, DELETE, POST

表明它允许跨域请求包含content-type头



Access-Control-Allow-Header: content-type

表明它允许cookies



Access-Control-Allow-Credentials:true



3.JSONP

利用script标签不受同源策略的影响,动态添加script标签,用于发起跨域请求。

eg1: 普通script标签请求

 <script>
    // getData即是回调函数的名称,传到后台,后台返回数据拿到结果进行相关逻辑操作。
     function getData(res) {
     console.log(res);
  	}

 $(document).ready(function () {
   $("#dom").click(function () {
         //往头部输入一个脚本,该脚本发起一个跨域请求
        $("head").append("<script src='http://localhost:9999/api?callback=getData'></script>");
       });

     });
 </script>

eg2: jquery的jsonp请求

 <script> 
      $(document).ready(function () {
            $("#dom").click(function () {
                $.ajax({
                     url: "http://localhost:9999",
                     // jsonp方式不支持post
                     type: "GET",
                     dataType: "jsonp", //不能少
                     success: function (res) {
            			 console.log(res);
                     }
                 });
            });
         });
 </script>



4.Nginx

目前大多数都是前后端分离,开发环境中跨域的问题是最需要先解决的。

web前台:

http://10.100.23.127:8888


后台接口:

http://10.100.23.126:9999/api


nginx配置如下

   server {
        listen       80;  # 监听80端口
        server_name  localhost;  #当前服务的域名

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
		
		# 代理服务端接口
        location /api/ {
           rewrite  ^/api/(.*)$ /$1 break;
            proxy_pass http://10.100.23.126:9999/;# 代理接口地址
        }
        
		location / {
			proxy_pass http://10.100.23.127:8888;
			root   E:/tms;
			try_files $uri $uri/ @router2;
			index index.html;
		}
 }  



版权声明:本文为Wcharles666原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。