react访问springBoot项目跨域问题

react访问springBoot项目跨域问题

java类AccessControlAllowOriginFilter

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.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

@WebFilter(filterName = "myFilter",urlPatterns = "/*")
public class AccessControlAllowOriginFilter 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-Headers", "Origin, X-Requested-With, Content-Type, Accept, " +
                "WG-App-Version, WG-Device-Id, WG-Network-Type, WG-Vendor, WG-OS-Type, WG-OS-Version, WG-Device-Model, WG-CPU, WG-Sid, WG-App-Id, WG-Token");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(req, response);
   } 
 
   public void init(FilterConfig filterConfig) {
 
   } 
 
   public void destroy() {
 
   } 

}

启动类配置

@SpringBootApplication
@ServletComponentScan      // 此处打开filter的扫描
public class BDAdminApplication {

    public static void main(String[] args) {
    	SpringApplication.run(BDAdminApplication.class, args);
    }
}

亲测有效

你可能感兴趣的:(Web前端技术)