前端ajax在局域网请求另一主机的后台跨域问题(解决)

Posted 根目录97

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了前端ajax在局域网请求另一主机的后台跨域问题(解决)相关的知识,希望对你有一定的参考价值。

1.这个方法不太妥当,不够安全,需要自己去写一个拦截器

web.xml配置指向拦截器

<filter>
        <filter-name>JsonFormat</filter-name>
        <filter-class>com.qianmo.qmyj.common.JsonFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>JsonFormat</filter-name>
        <url-pattern>*.do</url-pattern>
    </filter-mapping>
package com.qianmo.qmyj.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * FileName: ${NAME}
 * Author:   anpei
 * Date:     2017/5/16
 * Description:
 * History:
 */
@Component
public class JsonFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(getClass());


    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        logger.debug("------->受理HTTP请求,方式为:" + ((HttpServletRequest) req).getMethod() + "<------");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT,HEAD");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers","X-Requested-With,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials", "true");
//        response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");


//        String curOrigin = request.getHeader("Origin");
//        if (curOrigin != null) {
//            for (int i = 0; i < originProperties.length; i++) {
//                logger.debug("-------->允许跨域访问的来源是:" + originProperties[i] + "<---------");
//                if (curOrigin.equals(originProperties[i])) {
//                    response.setHeader("Access-Control-Allow-Origin", curOrigin);
//                }
//            }
//        } else { // 对于无来源的请求(比如在浏览器地址栏直接输入请求的),那就只允许我们自己的机器可以吧
//            response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1");
//        }
//        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT,HEAD");
//        request.setCharacterEncoding("UTF-8");
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("text/json");
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}

2.还有一个办法,我在eclipse里使用,是没有问题的,不过不知道为什么在idea里总是报错,因为时间关系,我也没深究,选择了上面的解决方法,也贴在下面吧。

----------------------web.xml-------------------------------------------------
<filter>
        <filter-name>CORS</filter-name>
        <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CORS</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
------------------------util工具类(CorsConfig)----------------------------------------
package com.commerce.utils;
//允许ajax跨域请求
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;

@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1
        corsConfiguration.addAllowedHeader("*"); // 2
        corsConfiguration.addAllowedMethod("*"); // 3
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4
        return new CorsFilter(source);
    }
}

引入两个jar

-------------------------pom.xml-------------------------------
<dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>5.0.0</version>
    </dependency>
    
    <dependency>
        <groupId>com.thetransactioncompany</groupId>
        <artifactId>cors-filter</artifactId>
        <version>2.5</version>
    </dependency>
package com.commerce.utils;
//允许ajax跨域请求
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;

@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1
        corsConfiguration.addAllowedHeader("*"); // 2
        corsConfiguration.addAllowedMethod("*"); // 3
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4
        return new CorsFilter(source);
    }
}

 

以上是关于前端ajax在局域网请求另一主机的后台跨域问题(解决)的主要内容,如果未能解决你的问题,请参考以下文章

ajax跨域请求接口介绍及解决方案

Ajax 跨域问题及其解决方案

前端设置请求头可以解决跨域问题吗

前端干活系列----ajax请求和跨域请求

ajax跨域请求解决方案

记录Spring Boot小项目的一些坑