1. 程式人生 > >Post request is No 'Access-Control-Allow-Origin' header is present on the requested resource跨域問題解決

Post request is No 'Access-Control-Allow-Origin' header is present on the requested resource跨域問題解決

跨域問題

報錯資訊為:post request is No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

原因:例如我們需要在A網址獲取B網的資源,由於A,B不在同一個域名之中導致出現了跨域訪問資源的情況。在瀏覽器的協議中,預設這樣的訪問是不安全的。跨域訪問被認為違反了同源策略,它規定只能訪問跟他html同源的資源
跨域限制是瀏覽器行為,不是伺服器行為。 瀏覽器認為位址列輸入時安全的,所以不限制認為是跨域。

如何解決跨域問題:在後臺新增過濾器,在需要跨域的請求體頭部新增Header屬性

首先新建過濾器的類

package com.jfly.apps.restful.springmvc;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import
javax.servlet.http.HttpServletResponse; public class CORSInterceptor 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; String origin = (String) servletRequest.getRemoteHost() + ":" + servletRequest.getRemotePort(); 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", "x-requested-with,Authorization,Content-Type"); response.setHeader("Access-Control-Allow-Credentials", "true"); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { } }

其次在web.xml中配置過濾器,完成

<filter>
    <filter-name>CORSInterceptor</filter-name>
    <filter-class>com.jfly.apps.restful.springmvc.CORSInterceptor</filter-class>
</filter>
<filter-mapping>
    <filter-name>CORSInterceptor</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>