前幾天剛發現了一跨域問題,本來吧跨域問題也挺好解決的。
網上搜點教程,該怎么配置就怎么配置就完事了。
但是今天這個跨域問題有點棘手,問題就出在127.0.0.1還是localhost上面
先放一下一開始在127.0.0.1解決跨域的代碼
前端
```HTML <!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Ajax Requests</title><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head><body><button id="sendPostRequest">Send Post Request</button><button id="sendGetRequest">Send Get Request</button><script>$("#sendPostRequest").click(function () {var stringValue = "caiyi";$.ajax({type: "POST",withCredentials: true,xhrFields: { withCredentials: true },url: "http://localhost:8081/testPost",data: "username=" + encodeURIComponent(stringValue),success: function (response) {console.log(response);},error: function (error) {console.log(error);}});});$("#sendGetRequest").click(function () {var customParam = "caiyi";$.ajax({type: "GET",withCredentials: true,xhrFields: { withCredentials: true },url: "http://localhost:8081/testGet/caiyi",success: function (response) {console.log(response);},error: function (error) {console.log(error);}});});</script> </body></html>
后端
package com.example.springmvcdemo.config;import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter;@Configuration public class GlobalCorsConfig {@Beanpublic CorsFilter corsFilter() {//1. 添加 CORS配置信息CorsConfiguration config = new CorsConfiguration();//放行哪些原始域config.addAllowedOrigin("http://127.0.0.1:5500/");//是否發送 Cookieconfig.setAllowCredentials(true);//放行哪些請求方式config.addAllowedMethod("*");//放行哪些原始請求頭部信息config.addAllowedHeader("*");//暴露哪些頭部信息config.addExposedHeader("*");//2. 添加映射路徑UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();corsConfigurationSource.registerCorsConfiguration("/**",config);//3. 返回新的CorsFilterreturn new CorsFilter(corsConfigurationSource);} }
接口:
package com.example.springmvcdemo.web;import org.springframework.web.bind.annotation.*;import javax.servlet.http.HttpSession;@RestController public class TestController {@PostMapping("/testPost")public String test(@RequestParam String username, HttpSession session){System.out.println(username);System.out.println(session);if (username != null){System.out.println(username);session.setAttribute(username,"測試session屬性");System.out.println("測試獲取:"+session.getAttribute(username));return "ok";}return "err";}@GetMapping("/testGet/{username}")public String test(HttpSession session, @PathVariable String username){System.out.println(username);System.out.println(session);System.out.println("get請求:"+session.getAttribute(username));return "ok";} }
但是問題就在于兩次請求前端并沒有帶上自身的cookie,通過查看請求可以發現請求回來的sessionid是不同的
而且控制臺打印出來的session對象也不是一個,但是!但是來了:
這里先科普下cors:
CORS (Cross-Origin Resource Sharing,跨域資源共享)是一個系統,它由一系列傳輸的HTTP頭組成,這些HTTP頭決定瀏覽器是否阻止前端 JavaScript 代碼獲取跨域請求的響應。
同源安全策略 默認阻止“跨域”獲取資源。但是 CORS 給了web服務器這樣的權限,即服務器可以選擇,允許跨域請求訪問到它們的資源。
- Access-Control-Allow-Origin
- 指示請求的資源能共享給哪些域。
- Access-Control-Allow-Credentials
- 指示當請求的憑證標記為 true 時,是否響應該請求。
當我打開控制臺查看響應頭的時候會發現這兩個屬性是被設置了的,這就說明我們的后端cors配置已經生效了!
但是為什么會不好使呢?
于是我經過各種百度之后懷疑會不會是127.0.0.1這個域名的問題,于是吧前端啟動的服務端口由127.0.0.1改到localhost,并修改對應的后端cors跨域配置
問題出奇的解決了,但我百思不得其解
修改后的后端代碼:
package com.example.springmvcdemo.config;import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter;@Configuration public class GlobalCorsConfig {@Beanpublic CorsFilter corsFilter() {//1. 添加 CORS配置信息CorsConfiguration config = new CorsConfiguration();//放行哪些原始域config.addAllowedOrigin("http://localhost:5500/");//是否發送 Cookieconfig.setAllowCredentials(true);//放行哪些請求方式config.addAllowedMethod("*");//放行哪些原始請求頭部信息config.addAllowedHeader("*");//暴露哪些頭部信息config.addExposedHeader("*");//2. 添加映射路徑UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();corsConfigurationSource.registerCorsConfiguration("/**",config);//3. 返回新的CorsFilterreturn new CorsFilter(corsConfigurationSource);} }
希望路過的各路大神可以指點一下,初步懷疑可能是springmvc的跨域配置不支持127.0.0.1,或者瀏覽器的同源策略有什么其他的隱形附加條件(已迷茫)