跨域
官网:https://developer.mozilla.org/zh-CN/docs/Learn
跨域访问不到页面
Access to fetch at 'http://localhost:8080/cors?callback=aaa' from origin 'http://127.0.0.1:8848' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. test.html:1 Uncaught (in promise) TypeError: Failed to fetch
后台服务器:

@RequestMapping("/rrr") @ResponseBody public String rrr(@RequestParam(defaultValue = "callback") String callback, HttpServletResponse response){ System.out.println(callback); response.setHeader("Access-Control-Allow-Origin","*"); return callback+"('rrr')"; } @RequestMapping("/cors") @ResponseBody public String test(@RequestParam(defaultValue = "callback") String callback){ System.out.println(callback); return callback+"('cors')"; }
html代码

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <script src="http://code.jquery.com/jquery.js"></script> <body> <button onclick="aa() "> aa()开始</button> <script> function aa(){ if(window.confirm("是否发送?")){ fetch("http://localhost:8080/cors?callback=aaa",{ method:"get" }).then(function(res){ resp.text().then(function(data){ console.log(data); }); }) } else { fetch("http://localhost:8080/rrr?callback=aaa",{ method:"get" }).then(function(res){ res.text().then(function(data){ console.log(data); }) }) } } </script> </body> </html>
用idea使用localhost:8080启动项目 用HBuilder127.0.1测试
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下