我想要一個 Javascript 函式將資料發送到 Spring 控制器并獲得回應。然而,由于嚴格的跨域參考策略,請求不會通過。
彈簧控制器:
@Controller
public class EventController {
@ResponseBody
@RequestMapping(value = "/event", method = RequestMethod.POST)
public String handleAjax(@RequestParam Integer id, HttpServletRequest request, HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*");
return "OK";
}
}
Javascript 函式:
function getContextPath() {
return window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
}
function move(moveDir,velocity){
$.ajax({
type : "POST",
url : getContextPath() "/event",
success: function(data){
console.log(data)
}
});
}
我知道我必須允許這些檔案的跨域。到目前為止,我嘗試的東西都不起作用。我嘗試過的清單:
-> 添加@CrossOrigin(origins = "http://localhost:8081", maxAge = 3600)到控制器
-> 添加response.setHeader("Access-Control-Allow-Origin", "*");到控制器
-> 添加crossorigin="anonymous"到 Javascript<script>標簽
uj5u.com熱心網友回復:
您的代碼將不起作用,因為您指定僅支持 POST 方法
@RequestMapping(value = "/event", method = RequestMethod.POST)
CORS 中的預檢請求需要 OPTIONS 方法。
因此,您還必須支持 POST 和 OPTIONS 才能使其作業。
@RequestMapping(value = "/event")
@RequestMapping(value = "/event", method = { RequestMethod.POST, RequestMethod.OPTIONS })
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS
uj5u.com熱心網友回復:
我終于明白了。有兩個問題。
第一個是,我不得不將它添加標題到AJAX請求,以允許請求由服務器處理:headers: { 'Access-Control-Allow-Origin': '/path_to_request_target' },。放置'*'而不是'/path_to_request_target'也可以。
第二個是我的調度程式 servlet。我不得不.html在 URL 的末尾加上 : url : getContextPath() "/event.html",。這是由于我的調度程式 servlet 的映射:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/index.jsp</url-pattern>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
添加.html到URL,因為作業的<url-pattern>*.html</url-pattern>。添加一個<url-pattern>滿足初始 URL 格式的也可以。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/360453.html
標籤:阿贾克斯 春天 弹簧 mvc 跨域读取阻塞 跨源资源策略
