axios spring 解决跨域问题

2018-07-06  本文已影响0人  yfmei

配置webpack的代理很简单

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
          // 所有 /bleview 开头的请求都会代理到 http://localhost:8080/,
          // 也就是如果服务器登录的url: http://localhost:8080/bleview/login, 请求url只需要写 /bleview/login 即可
          '/bleview': {
            target: 'http://localhost:8080/',
            changeOrigin: true
          }
        },
    ...
  }
}

只能在开发模式下有效

axios + 服务器配置

axios 单独设置没用, 需要服务器支持才允许跨域


const service = axios.create({
  baseURL: "http://localhost:8080", // 设置请求前缀
  
  // 设置代理, 没用
  // proxy: {
  //   host: "localhost",
  //   port: 8080
  // },
  // withCredentials: true, // 跨域时携带cookie等认证信息
  // 设置请求头允许跨域, 没用
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    // "Access-Control-Allow-Origin": "http://localhost:8081",
    // "Access-Control-Allow-Methods": "GET, POST, PATCH, PUT, DELETE, OPTIONS",
    // "Access-Control-Allow-Headers": "Origin, Content-Type, X-Auth-Token"
  },
}

后台

response.setHeader("Access-Control-Allow-Origin", "*"); // 不能设置为 * , 
response.setHeader("Access-Control-Allow-Origin", "http://localhost:8081"); // 要设置为指定ip
@Configuration
public class WebMvcConfg extends WebMvcConfigurerAdapter {
  // todo 废弃
}

@Configuration
public class WebMvcConfg extends WebMvcConfigurationSupport {
  // todo 不推荐
}

// 推荐
@Configuration
public class WebMvcConfg implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("http://localhost:8081")
                .allowedMethods("PUT", "DELETE")
                .allowedHeaders("header1", "header2", "header3")
                .exposedHeaders("header1", "header2")
                .allowCredentials(false).maxAge(3600);
    }
}
@CrossOrigin(origins = "http://localhost:8081", maxAge = 3600)
@Controller

@CrossOrigin(origins = "http://localhost:8081", maxAge = 3600)
@RequestMapping
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 允许跨域
 */
public class MyCorsFilter extends CorsFilter  {

    public MyCorsFilter() {
        super(configurationSource());
    }

    private static UrlBasedCorsConfigurationSource configurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:8081");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}
public class MyCorsFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        // httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        // 携带cookie不能使用通配符 Access-Control-Allow-Origin=*
        httpResponse.setHeader("Access-Control-Allow-Origin", httpRequest.getHeader("Origin"));
        // httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        // httpResponse.setHeader("Access-Control-Max-Age", "3600");
        // httpResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
        // httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
<!--web.xml-->

<filter>
    <filter-name>MyCorsFilter</filter-name>
    <filter-class>com.ai.ble.base.interceptor.MyCorsFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>MyCorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
上一篇 下一篇

猜你喜欢

热点阅读