springboot跨域测试

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() {}
}

在这里插入图片描述

项目代码

源码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乘茶蛙泳

just 4 fun

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值