前后端分離ckeditor跨域問題處理
這個跨域問題很常見,特別是前后端分離的情況,IP地址不同導致了頁面跨域,具體原因大多是因為前端ifame問題
分析
ckeditor插件里config.js需要配置
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寫回到了前端頁面,這個時候總是會容易引起跨域
解決方案
在前端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); }
結語
親測這樣能夠解決頁面跨域問題
