SpringBoot+ajax跨域请求 发表于 2019-07-11 | 更新于 2024-03-14
| 阅读量:
在使用ajax请求SpringBoot + SpringSecurity后端时遇到的一些坑。
<The rest of contents | 余下全文>
不集成SpringSecurity的情况下进行跨域访问 错误信息 在使用ajax请求后端的时候在浏览器控制台会输出如下信息:
1 Access to XMLHttpRequest at 'http://localhost:8080/test' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
从源’本地路径’访问 ‘目标路径(请求链接)’文本传输请求已被CORS策略阻塞:对预置请求的响应未通过访问控制检查:请求的资源上不存在’Access- control - allow - origin ‘报头。
错误原因 本地路径和目标路径不是同一个域名下引起的跨域问题
解决方案 在对应的Controller类前上@CrossOrigin注解
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 package com.example.demo.controller;import org.springframework.web.bind.annotation.CrossOrigin;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RestController;@RestController @CrossOrigin public class TestController { @PostMapping("/testPost") public String testPost () { System.out.println("testPost成功" ); return "testPost跨域请求成功" ; } @GetMapping("/testGet") public String testGet () { System.out.println("testGet成功" ); return "testGet跨域请求成功" ; } }
集成SpringSecurity的情况下进行跨域访问 错误信息 集成SpringSecurity后get请求正常,但是对于post请求仍然会显示错误信息
1 2 jquery.min.js:4 POST http: list_student.html:1 Access to XMLHttpRequest at 'http://localhost:8080/testPost' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
解决方案 添加WebSecurityConfiguration配置文件可关闭csrf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 package com.example.demo;import org.springframework.context.annotation.Configuration;import org.springframework.core.annotation.Order;import org.springframework.http.HttpMethod;import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) @Order(-1) public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure (HttpSecurity http) throws Exception { http.requestMatchers().antMatchers(HttpMethod.OPTIONS, "/oauth/**" ) .and() .cors() .and() .csrf().disable(); } }