SpringBoot處理跨域請求

CORS全稱爲Cross Origin Resource Sharing(跨域資源共享), 每一個頁面需要返回一個名爲Access-Control-Allow-Origin的http頭來允許外域的站點訪問,你可以僅僅暴露有限的資源和有限的外域站點訪問。

如果一個請求需要允許跨域訪問,則需要在http頭中設置Access-Control-Allow-Origin來決定需要允許哪些站點來訪問。如假設需要允許https://www.xxx.com這個站點的請求跨域,則可以設置:

Access-Control-Allow-Origin:https://www.xxx.com
  • 使用@CrossOrigin註解

Controller上使用@CrossOrigin註解,該類下的所有接口都可以通過跨域訪問

@RequestMapping("/api")
@RestController
@CrossOrigin("https://www.xxx.com") //只有指定域名可以訪問該類下所有接口
public class CorsTestController {
    @GetMapping("/sayHello")
    public String sayHello() {
        return "hello world";
    }
}
  • CORS全局配置-實現WebMvcConfigurer

新建跨域配置類:CorsConfig.java

package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 跨域配置
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Bean
    public WebMvcConfigurer corsConfigurer()
    {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").
                        allowedOrigins("https://www.xxx.com"). //允許跨域的域名,可以用*表示允許任何域名使用
                        allowedMethods("*"). //允許任何方法(post、get等)
                        allowedHeaders("*"). //允許任何請求頭
                        allowCredentials(true). //帶上cookie信息
                        exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L); //maxAge(3600)表明在3600秒內,不需要再發送預檢驗請求,可以緩存該結果
            }
        };
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章