Spring前后端跨域請求設(shè)置代碼實例
前后端項目分離,跨域請求時,后端的兩種配置方式:
1.配置類:
package com.helq3.config;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;/** * 跨域全局配置 */@Configurationpublic class CorsConfig { private CorsConfiguration buildConfig(){ CorsConfiguration configuration = new CorsConfiguration(); //設(shè)置屬性 //允許跨域請求的地址,*表示所有 configuration.addAllowedOrigin('*'); //配置跨域的請求頭 configuration.addAllowedHeader('*'); //配置跨域的請求方法 configuration.addAllowedMethod('*'); //表示跨域請求的時候使用的是否是同一個session configuration.setAllowCredentials(true); return configuration; } @Bean public CorsFilter corsFilter(){ UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration('/**',buildConfig()); return new CorsFilter(source); }}
2.Controller上面配置
@CrossOrigin(origins = '*',allowedHeaders = '*',methods = {},allowCredentials = 'true')public class TestController {}
3.Ant Design Vue 中,在src/util/request.js中增加
axios.defaults.withCredentials = true
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python 實現(xiàn)勞拉游戲的實例代碼(四連環(huán)、重力四子棋)2. Python+unittest+requests 接口自動化測試框架搭建教程3. Java GZip 基于內(nèi)存實現(xiàn)壓縮和解壓的方法4. jsp+servlet簡單實現(xiàn)上傳文件功能(保存目錄改進)5. JavaScript數(shù)據(jù)結(jié)構(gòu)之雙向鏈表6. 利用CSS制作3D動畫7. 一款功能強大的markdown編輯器tui.editor使用示例詳解8. 存儲于xml中需要的HTML轉(zhuǎn)義代碼9. SpringBoot+TestNG單元測試的實現(xiàn)10. .Net加密神器Eazfuscator.NET?2023.2?最新版使用教程
