问题: 当我们在自己的个人电脑上去进行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)
搞定收工:
文章来源:https://www.toymoban.com/news/detail-609668.html
文章来源地址https://www.toymoban.com/news/detail-609668.html
到了这里,关于Vue调用后端api接口出现跨域问题,只要三步解决问题的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!