响应前端调用JS函数
大约 1 分钟languagejava
无 nginx 代理
war包运行在 tomcat 中或者 springboot 中通过 thymleaf 将前后端融合在一个应用中时,可通过下面方法在 java 响应给前端结果时调用 JS 函数
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void upload(MultipartFile file, String fileRename, String remark,
Integer parentId, ServletResponse res) throws IOException {
PrintWriter writer = res.getWriter();
writer.print("<script>parent.afterUpload()</script>");
}
保证前端当前页面中有函数 afterUpload 即可。来自染厂ERP 类 BillorderdetailImgController 中的方法 upload
nginx 代理+前后分离
前后分离的项目通过 nginx 解决跨域问题,同时要在反向代理后端请求的 location 中设置N多 header
location /shunjiebe {
proxy_set_header Host $host;
proxy_set_header Cookie $http_cookie;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
proxy_pass http://127.0.0.1:7073/shunjiebe;
proxy_redirect http://127.0.0.1:7073/shunjiebe /shunjiebe;
proxy_cookie_path /shunjiebe /shunjiebe;
}
java 端响应给前端时也不能简单就写一行 JS 代码,而应该写一个完整的 html 页面
@PostMapping("/upload")
public void upload(MultipartFile file, String fileRename, String remark,
Integer parentId, ServletResponse res) throws IOException {
// 设置响应的内容类型为text/html
res.setContentType("text/html");
// 获取输出流
PrintWriter out = res.getWriter();
// 写入HTML内容和JavaScript代码
out.println("<html>");
out.println("<head>");
out.println("<title>Example Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet Example</h1>");
out.println("<script>");
out.println("parent.afterUpload();"); // 调用前端JavaScript函数
out.println("</script>");
out.println("</body>");
out.println("</html>");
}
允许 iframe
使用 iframe + form 上传文件时如果出现禁用 iframe 的问题将下面代码写在 nginx 的 server 下
proxy_hide_header X-Frame-Options;
add_header X-Frame-Options "ALLOWALL";
也可以用在 location 下
