這個跨域問題很常見,特別是先後端分離的狀況,IP地址不一樣致使了頁面跨域,具體緣由大可能是由於前端ifame問題javascript
ckeditor插件裏config.js
須要配置html
config.filebrowserImageUploadUrl="http://127.0.0.1:8085/upload"
這個地址就是日後端請求的地址,會帶一個CKEditorFuncNum
參數到後臺,當時接收到這個以後我是用了response又給寫回去了前端
@PostMapping("/upload") public void ckeditor(@RequestParam("upload") MultipartFile filePath, HttpServletRequest request, HttpServletResponse response) throws IOException { String imageUrl = upload(filePath); String callback = request.getParameter("CKEditorFuncNum"); // 結合ckeditor功能 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<script type=\"text/javascript\">"); out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + imageUrl + "',''" + ")"); out.println("</script>"); out.flush(); out.close();
將文件上傳後取得URL地址後,經過response將JS寫回到了前端頁面,這個時候老是會容易引發跨域java
在前端index.html同級目錄下新增一個頁面,隨便取名,我叫getimage.html
後端
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title></title> </head> <body> <script> function GetQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); //獲取url中"?"符後的字符串並正則匹配 var context = ""; if (r != null) context = r[2]; reg = null; r = null; return context == null || context == "" || context == "undefined" ? "" : context; } window.parent.CKEDITOR.tools.callFunction(GetQueryString("CKEditorFuncNum"),GetQueryString("ImageUrl"),GetQueryString("Message")); </script> </body> </html>
再修改一下後端的接口跨域
@PostMapping("/upload") public void ckeditor(@RequestParam("upload") MultipartFile filePath, HttpServletRequest request, HttpServletResponse response) throws IOException { String imageUrl = upload(filePath); String callback = request.getParameter("CKEditorFuncNum"); // 獲取請求地址,拼接static目錄下與index.html同級的getimage頁面 String backUrl = request.getHeader("Origin") + "/getimage.html"; response.sendRedirect(backUrl+"?ImageUrl="+imageUrl+"&CKEditorFuncNum="+callback); }
親測這樣可以解決頁面跨域問題app