H5请求后台接口跨域问题

前端页面与后台运行在不同的服务器时,就会出现跨域这一问题

此为后台处理方式:加一个拦截处理,对responsede header添加一些属性

定义一个类并实现Filter接口 Override doFilter方法,具体代码如下

package com.ocp.comm.aspect;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author dwj
 * @description
 * @date 2022/1/27 16:55
 */
@Component
@WebFilter(urlPatterns = "/*", filterName = "indexFilter")
public class CORSFilter implements Filter {

    @Override
    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-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {

    }

    public void destroy() {

    }


}

配置完后重启项目访问即可解决跨域问题。

你可能感兴趣的:(SpringBoot,java,前端)