问题: 当我们在自己的个人电脑上去进行vue调用后端的操作时,经常会遇到跨域问题

解决方式:

1.在Vue项目中调用api接口的地方加上

'Access-Control-Allow-Origin': '*'

2.在后端代码项目重写Filter类

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

@WebFilter(filterName = "CorsFilter")
public class CorsFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

        filterChain.doFilter(servletRequest, servletResponse);
    }


    @Override
    public void destroy() {

    }
}

3. 在控制类方法上加上允许跨域的注解

@CrossOrigin(origins = "*", maxAge = 3600)

搞定收工:

 

Logo

前往低代码交流专区

更多推荐