前端vue运行在80端口
后端运行在8080端口
axios报错:
Access to XMLHttpRequest at 'http://127.0.0.1:8080/emp' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
解决方法
在controller类中添加注解
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin(origins = {"http://localhost:8080"}, maxAge = 3600)
添加一个配置类
package com.example.guanlixitong.config;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// 初始化方法
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
// 设置允许跨域请求的域名和请求头信息
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
httpResponse.setHeader("Access-Control-Allow-Methods", "*");
httpResponse.setHeader("Access-Control-Allow-Headers", "*");
chain.doFilter(request, response);
}
@Override
public void destroy() {
// 销毁方法
}
}
在application.properties配置
spring.servlet.filter.order=0
spring.servlet.filter.name=corsFilter
spring.servlet.filter.type=generic
spring.servlet.filter.enabled=true