1. 程式人生 > >Spring Boot 解決跨域問題

Spring Boot 解決跨域問題

一、@CrossOrigin註解方式 Controller method CORS configuration

這裡我們在users對映的方法getUserList上面加上@CrossOrigin

    @CrossOrigin
    @RequestMapping(value = "users", method = RequestMethod.GET)
    public ResponseEntity<JsonResult> getUserList ()

表示跨域問題解決。 default @CrossOrigin allows all origins and the HTTP methods specified in the @RequestMapping annotation 上面的官方文件說明,也就是預設的@CrossOrigin允許所有跨域請求。

通過檢視CrossOrigin原始碼可以看到, 預設配置為:

"Access-Control-Allow-Origin" : "*"
"Access-Control-Allow-Methods" : "GET,POST,PUT,OPTIONS"
"Access-Control-Allow-Credentials" : "true"
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CrossOrigin
{
/** @deprecated */ @Deprecated String[] DEFAULT_ORIGINS = new String[]{"*"}; /** @deprecated */ @Deprecated String[] DEFAULT_ALLOWED_HEADERS = new String[]{"*"}; /** @deprecated */ @Deprecated boolean DEFAULT_ALLOW_CREDENTIALS = true; /** @deprecated */ @Deprecated
long DEFAULT_MAX_AGE = 1800L; @AliasFor("origins") String[] value() default {}; @AliasFor("value") String[] origins() default {}; String[] allowedHeaders() default {}; String[] exposedHeaders() default {}; RequestMethod[] methods() default {}; String allowCredentials() default ""; long maxAge() default -1L; }

二、It is also possible to enable CORS for the whole controller 也可以用在整個Controller類上面。即該controller所有對映都支援跨域請求。

@CrossOrigin(origins = "http://domain2.com",maxAge = 3600,methods = {RequestMethod.GET, RequestMethod.POST})
@RestController
public class UserController