美文网首页
SpringBoot跨域问题,POST请求报No 'Access

SpringBoot跨域问题,POST请求报No 'Access

作者: 憨厚老实的老赵 | 来源:发表于2018-05-11 17:42 被阅读0次

    SpringBoot基于1.5.8版本。
    前端框架用的是vue.js
    刚开始按照网上的贴子把Access-Control-Allow-Origin设置为*,get请求没有问题能够成功跨域请求。

    import org.slf4j.Logger;
    import org.springframework.stereotype.Component;
    
    import javax.servlet.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    /**
     * 允许跨域请求
     */
    @Component
    public class CorsFilter implements Filter {
    
        final static Logger logger = org.slf4j.LoggerFactory.getLogger(CorsFilter.class);
    
    
    
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
    
            HttpServletRequest reqs = (HttpServletRequest) req;
    
            response.setHeader("Access-Control-Allow-Origin","*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");
            chain.doFilter(req, res);
        }
        public void init(FilterConfig filterConfig) {}
        public void destroy() {}
    }
    

    但是在提交表单的时候是用的post请求这时候就一直报No 'Access-Control-Allow-Origin' header is present on the requested
    只好换一种写法了:

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    @Configuration
    public class CorsConfig  extends WebMvcConfigurerAdapter {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowCredentials(true)
                    .allowedMethods("GET", "POST", "DELETE", "PUT")
                    .maxAge(3600);
        }
    }
    

    SUCCESS!

    相关文章

      网友评论

          本文标题:SpringBoot跨域问题,POST请求报No 'Access

          本文链接:https://www.haomeiwen.com/subject/flfqdftx.html