> For the complete documentation index, see [llms.txt](https://jack80342.gitbook.io/spring-boot/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jack80342.gitbook.io/spring-boot/iv.-spring-boot-features/27.-developing-web-applications/27.1.-the-spring-web-mvc-framework/27.1.13.-cors-support.md).

# 27.1.13. CORS支持

[跨域资源共享](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)（CORS）是一个[大多数浏览器](https://caniuse.com/#feat=cors)都实现了的[W3C标准](https://www.w3.org/TR/cors/)，它允许你以灵活的方式指定跨域请求如何被授权，而不是采用那些不安全，性能低的方式，比如IFRAME或JSONP。

从4.2版本开始，Spring MVC对[CORS](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/web.html#cors)提供开箱即用的支持。不用添加任何特殊配置，只需要在Spring Boot应用的controller方法上注解[`@CrossOrigin`](https://docs.spring.io/spring/docs/5.0.4.RELEASE/javadoc-api/org/springframework/web/bind/annotation/CrossOrigin.html)，并添加[CORS配置](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/web.html#controller-method-cors-configuration)。通过注册一个自定义`addCorsMappings(CorsRegistry)`方法的`WebMvcConfigurer` bean可以指定[全局CORS配置](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/web.html#global-cors-configuration)：

```java
@Configuration
public class MyConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**");
            }
        };
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jack80342.gitbook.io/spring-boot/iv.-spring-boot-features/27.-developing-web-applications/27.1.-the-spring-web-mvc-framework/27.1.13.-cors-support.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
