Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 530|回复: 0

解决ajax跨域请求问题

[复制链接]
  • TA的每日心情
    奋斗
    2024-11-24 15:47
  • 签到天数: 804 天

    [LV.10]以坛为家III

    2053

    主题

    2111

    帖子

    72万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    726782
    发表于 2021-6-23 08:06:44 | 显示全部楼层 |阅读模式

    自己做网站的时候,经常遇到跨域问题,下面是平时多次实践总结出的解决方法,大家有什么更好的思路,可以相互交流下~
    XMLHttpRequest cannot load http://www.imooc.com/data/check_f.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
    解决方法:跨源问题,添加cors。
    1.filter或者servlet里面添加response.setHeader("Access-Control-Allow-Origin", "");2.response.setHeader("Access-Control-Allow-Origin", "");放到接收客户端api 的地方
    3.如果是servlet的话就放到get或者post方法里面,jsp页面就扔到第一行
    4.如果是filter部署就扔到dofilter()

    ---------------------------------springmvc---------------------------------

    添加SimpleCORSFilter.java

    import java.io.IOException;
    
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.stereotype.Component;
    
    @Component
    public class SimpleCORSFilter implements Filter {
    
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
             //response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    
                                                                                                            // response.setContentType("text/html;charset=UTF-8");
               // response.setHeader("Access-Control-Allow-Origin", "*");
               // response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
               // response.setHeader("Access-Control-Max-Age", "0");
               // response.setHeader("Access-Control-Allow-Headers", "Authentication, Origin, Accept, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, token");
               // response.setHeader("Access-Control-Allow-Credentials", "true");
               // response.setHeader("XDomainRequestAllowed","1");
    
            chain.doFilter(req, res);
        }
    
        public void init(FilterConfig filterConfig) {}
    
        public void destroy() {}
    
    }
    

    web.xml添加

    <filter>
        <filter-name>SimpleCORSFilter</filter-name>
        <filter-class>com.zhcs.context.SimpleCORSFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>SimpleCORSFilter</filter-name>
        <url-pattern>/app/*</url-pattern>
    </filter-mapping>
    

    --------------------------------------OR-------------------------------------

    添加 CorsConfigureAdapter.java

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    @Configuration
    @EnableWebMvc
    public class CorsConfigureAdapter extends WebMvcConfigurerAdapter {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            super.addCorsMappings(registry);
            registry.addMapping("/**");
        }
    }
    

    在Controller上或方法上使用@CrossOrigin注解

    @CrossOrigin(maxAge = 3600)
    

    --------------------------------------xml-------------------------------------

    <mvc:cors>
        <mvc:mapping path="/**" />
    </mvc:cors>
    <mvc:cors>
        <mvc:mapping path="/api/**" allowed-origins="http://domain1.com, http://domain2.com" allowed-methods="GET, PUT" allowed-headers="header1, header2, header3" exposed-headers="header1, header2" allow-credentials="false" max-age="123" />
        <mvc:mapping path="/resources/**" allowed-origins="http://domain1.com" />
    </mvc:cors>
    

    --------------------------------------Nginx支持跨域请求--------------------------------------

    location /{
        add_header 'Access-Control-Allow-Origin' 'http://other.subdomain.com';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET'; 
        ...
        the rest of your configuration here
        ...
    }
    
    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2025-1-22 19:08 , Processed in 0.060700 second(s), 29 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表