今天遇到了這個情況,
在本地請求:
通過部署在別的服務器上的應用請求:
報錯:CORS 策略阻止了從源"http://leaf.elatis.cn"以"http://localhost:8080/mea"進行獲取的訪問:對預檢請求的響應未通過訪問控制檢查:請求的資源上不存在"訪問-控制-允許源"標頭。如果不透明響應滿足您的需要,則將請求模式設置爲"無 cors"以在禁用 CORS 時獲取資源。
COR
CORS是一個跨域資源共享方案,爲了解決跨域問題,通過增加一系列請求頭和響應頭,規範安全地進行跨站數據傳輸。
spring項目解決方案
如何使用
- 客戶端只需按規範設置請求頭。
- 服務端按規範識別並返回對應響應頭,或者安裝相應插件,修改相應框架配置文件等。具體視服務端所用的語言和框架而定
package me.treblez.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CORSConfiguation implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry){
registry
.addMapping("/**")
.allowedMethods("*")
.allowedOrigins("*")
.allowedHeaders("*");
}
}
addMapping:配置可以被跨域的路徑,可以任意配置,可以具體到直接請求路徑。
allowedMethods:允許所有的請求方法訪問該跨域資源服務器,如:POST、GET、PUT、DELETE等。
allowedOrigins:允許所有的請求域名訪問我們的跨域資源,可以固定單條或者多條內容,如:“http://www.baidu.com”,只有百度可以訪問我們的跨域資源。
allowedHeaders:允許所有的請求header訪問,可以自定義設置任意請求頭信息,如:“X-YAUTH-TOKEN”
現在就可以正常訪問了:
非spring項目解決方案
理論上我們可以通過“增加一系列請求頭和響應頭”來達到同樣的效果。
加一個過濾器即可
package me.treblez.demo.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
public class CorsFilter implements Filter {
/**
* Default constructor.
*/
public CorsFilter() {
}
/**
* @see Filter#destroy()
*/
public void destroy() {
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
String currentOrigin = request.getHeader("Origin");
response.setHeader("Access-Control-Allow-Origin", "*");
chain.doFilter(req, resp);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
}
}
深入理解WebMvcConfigurer接口
mark