加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajax 浏览器跨域问题的解决办法

发布时间:2020-12-16 03:32:55 所属栏目:百科 来源:网络整理
导读:参考链接:http://stackoverflow.com/questions/12383109/access-control-allow-origin-in-tomcat ajax 跨域访问报错: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xxxxxxx' is therefore not allowed a

参考链接:http://stackoverflow.com/questions/12383109/access-control-allow-origin-in-tomcat

ajax 跨域访问报错:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xxxxxxx' is therefore not allowed access.

可以通过在 web.xml 中配置类似一个白名单这样的机制来解决跨域访问问题,下面是 web.xml 中的配置:

<filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
    <init-param>
        <param-name>cors.allowOrigin</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportedMethods</param-name>
        <param-value>GET,POST,HEAD,PUT,DELETE</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportedHeaders</param-name>
        <param-value>Content-Type,Last-Modified</param-value>
    </init-param>
    <init-param>
        <param-name>cors.exposedHeaders</param-name>
        <param-value>Set-Cookie</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportsCredentials</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>CORS</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

由于 com.thetransactioncompany.cors.CORSFilter 这个过滤器需要依赖一个 jar 包,所以还需要在 pom 文件中增加这样一个依赖,下面是 pom 文件中的依赖:

<dependency>
        <groupId>com.thetransactioncompany</groupId>
        <artifactId>cors-filter</artifactId>
        <version>1.3.2</version>
</dependency>

简单说一下:

<init-param>
        <param-name>cors.allowOrigin</param-name>
        <param-value>*</param-value>
</init-param>
  • cors.allowOrigin 就是信任的白名单
  • * 代表所有的域都可以访问,浏览器限制跨域访问本来是浏览器的一种安全机制。现在我们把白名单配置为允许所有的域都能访问是不安全的。所以,大家最好根据实际情况,仅把自己需要信任的域加进去,把 * 号替换掉,这样一来其他的域就不能跨域访问自己的网站,提高了安全性。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读