我的AJAX通话和服务都还可以。在互联网上搜索了很多之后,我发现它的服务器端问题不是客户端问题。
在Spring的服务器端,我们必须实现允许CORS请求的过滤器。
过滤器将如下所示。
import java.io.IOException;import javax.servlet.FilterChain;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.springframework.web.filter.OncePerRequestFilter;public class CORSFilter extends oncePerRequestFilter { private static final Log LOG = LogFactory.getLog(CORSFilter.class); @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { response.addHeader("Access-Control-Allow-Origin", "*"); if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) { LOG.trace("Sending Header...."); // CORS "pre-flight" request response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); // response.addHeader("Access-Control-Allow-Headers", "Authorization"); response.addHeader("Access-Control-Allow-Headers", "Content-Type"); response.addHeader("Access-Control-Max-Age", "1"); } filterChain.doFilter(request, response); }}
并在web.xml中将此过滤器应用于您的服务请求,如下所示
<filter> <filter-name>cors</filter-name> <filter-class>com.test.common.controller.CORSFilter</filter-class> <!-- your package name and filter class --> </filter> <filter-mapping> <filter-name>cors</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
这可能会帮助遇到此问题的其他人。:)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)