controller
@RestController
@RequestMapping("demo")
public class DemoController {
@PostMapping("test")
public Map<String,Object> test(@RequestBody Map<String,Object> params) {
Map<String,Object> result = new HashMap<>();
result.put("code", "0");
result.put("msg", "成功");
return result;
}
}
js代码
- 打包成网页 index.html
- 在本地的tomcat的webapps目录下,创建test目录,放入 index.html
- 启动tomcat
- 浏览器访问 http://localhost:8080/test/index.html
<!DOCTYPE html>
<html>
<head>
<title>测试跨域</title>
</head>
<body>
<button id="testButton">test</button>
<script>
document.getElementById("testButton").addEventListener("click", async () => {
const testData = {
title: "hi!"
};
const response = await fetch("http://localhost:8081/demo/test", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(testData),
//credentials: "include" // Add this line to include credentials
});
if (response.ok) {
const responseData = await response.json();
console.log("test successful:", responseData);
} else {
console.error("test failed");
}
});
</script>
</body>
</html>
测试结果
报错:Access to fetch at ‘http://localhost:8081/demo/test’ from origin ‘http://localhost:8080’ 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.
springboot 加上跨域配置后
@Component
@WebFilter("/*")
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Max-Age", "3600");
if (!"OPTIONS".equalsIgnoreCase(request.getMethod())) {
chain.doFilter(req, res);
}
}
@Override
public void init(FilterConfig filterConfig) {}
@Override
public void destroy() {}
}