我实际上在SrpingBoot后端工作。
为了解决CORS问题,我使用了我们随处可见的简单过滤器。
@Component
public class CORSResponseFilter implements Filter {
@Override
public void init(FilterConfig arg0) throws ServletException {}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response=(HttpServletResponse) resp;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, resp);
}
@Override
public void destroy() {}
}
此过滤器将添加到此处的配置中:
public class ApplicationConfiguration extends ResourceConfig {
public ApplicationConfiguration() {
super();
// Create a recursive package scanner
PackageNamesScanner resourceFinder = new PackageNamesScanner(
new String[] { "X.service" }, true);
// Register the scanner with this Application
registerFinder(resourceFinder);
register(JacksonFeature.class);
// Mise en place du filtre
register(CORSResponseFilter.class);
}
}
但我仍然遇到这个错误:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
我错过了什么?
答案 0 :(得分:-2)
端口问题,与代码无关。