前后端分离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);
}
结语
亲测这样能够解决页面跨域问题