springBoot(9):web開發-CORS支持
一、簡介
Web 開發經常會遇到跨域問題,解決方案有:jsonp,iframe,CORS 等等
1.1、CORS與JSONP相比
1、JSONP只能實現GET請求,而CORS支持所有類型的HTTP請求。
2、使用CORS,開發者可以使用普通的XMLHttpRequest發起請求和獲得數據,比起JSONP 有更好的錯誤處理。
3、JSONP主要被老的瀏覽器支持,它們往往不支持CORS,而絕大多數現代瀏覽器都已經支持了CORS瀏覽器支持情況
Chrome 3+
Firefox 3.5+
Opera 12+
Safari 4+
Internet Explorer 8+
二、實現CORS
說明:在springMVC中可以配置全局的規則,[email protected]
2.1、全局配置
方式一:註冊bean
package com.example.demo.utils.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * Created by DELL on 2017/6/18. */ @Configuration public class CustomCorsConfiguration { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**").allowedOrigins("http://localhost:8080"); } }; } }
說明:表示對於/api請求下的所以資源,允許http://localhost:8080訪問
方式二:繼承WebMvcConfigurerAdapter
package com.example.demo.utils.configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * 跨域請求處理 * @Author: 我愛大金子 * @Description: 跨域請求處理 * @Date: Created in 10:12 2017/6/18 */ @Configuration public class CustomCorsConfiguration2 extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**").allowedOrigins("http://localhost:8080"); } }
說明:表示對於/api請求下的所以資源,允許http://localhost:8080訪問
2.2、細粒度配置
[email protected],如:@CrossOrigin(origins = "http://localhost:8080")
本文出自 “我愛大金子” 博客,請務必保留此出處http://1754966750.blog.51cto.com/7455444/1939451
springBoot(9):web開發-CORS支持