美文网首页
如何解决跨域问题

如何解决跨域问题

作者: Lucie_xxm | 来源:发表于2019-07-16 14:09 被阅读0次

使用 Java 配置的方式

/**
 * 跨域配置
 * <p>Title: CorsConfiguration</p>
 * <p>Description: </p>
 *
 * @author xxm
 * @version 1.0.0
 * @date 2018/3/8 22:56
 */
@Configuration
public class CORSConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(false).maxAge(3600);
    }
}

使用注解的方式

@CrossOrigin(origins = "*", maxAge = 3600)

使用 CORS(跨资源共享)解决跨域问题

在header里面设置(在 header 中设置:Access-Control-Allow-Origin)

使用 JSONP 解决跨域问题

用 JSONP 抓到的资料并不是 JSON,而是任意的 JavaScript,用 JavaScript 直译器执行而不是用 JSON 解析器解析(需要目标服务器配合一个 callback 函数)。

使用 Nginx 反向代理解决跨域问题

Nginx 配置跨域案例,在 nginx.conf 的 location 中增加如下配置:
add_header Access-Control-Allow-Origin *或域名;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;

如:

user  nginx;
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;

    keepalive_timeout  65;

    server {
        listen 80;
        server_name 192.168.75.128;
        location / {
            add_header Access-Control-Allow-Origin *;
            add_header Access-Control-Allow-Headers X-Requested-With;
            add_header Access-Control-Allow-Methods GET,POST,OPTIONS;

            root /usr/share/nginx/wwwroot/cdn;
            index index.jsp index.html index.htm;
        }
    }
}

解决跨域后的效果图

相关文章

网友评论

      本文标题:如何解决跨域问题

      本文链接:https://www.haomeiwen.com/subject/fdzzkctx.html