SpringBoot solves ajax cross-origin problems. springbootajajax cross-Origin

Source: Internet
Author: User

SpringBoot solves ajax cross-origin problems. springbootajajax cross-Origin
1. Method 1:

1. Compile a Configuration that supports cross-origin requests.

Import org. springframework. context. annotation. configuration; import org. springframework. web. servlet. config. annotation. corsRegistry; import org. springframework. web. servlet. config. annotation. webMvcConfigurerAdapter; /*** cross-origin processing of AJAX requests * @ author Levin * @ time 2017-07-13 */@ Configurationpublic class CorsConfig extends WebMvcConfigurerAdapter {static final String ORIGINS [] = new String [] {" GET ", "POST", "PUT", "DELETE"}; @ Override public void addCorsMappings (CorsRegistry registry) {registry. addMapping ("/**"). allowedOrigins ("*"). allowCredentials (true ). allowedMethods (ORIGINS ). maxAge (3600) ;}2. HTTP request interface @ RestControllerpublic class HelloController {@ Autowired HelloService helloService; @ GetMapping (value = "/test", produces = MediaType. APPLICATION_JSON_UTF8_VALUE) public String query () {return "hello ";}}
Ii. method 2 (recommended)

PS: first, there is a problem. When the server throws 500, there is still a cross-origin problem.

@ SpringBootApplication @ ComponentScan @ EnableDiscoveryClientpublic class ManagementApplication {public static void main (String [] args) {SpringApplication. run (ManagementApplication. class, args);} private CorsConfiguration buildConfig () {CorsConfiguration corsConfiguration = new CorsConfiguration (); corsConfiguration. addAllowedOrigin ("*"); corsConfiguration. addAllowedHeader ("*"); corsConfiguration. addAllowedMethod ("*"); corsConfiguration. addExposedHeader (HttpHeaderConStant. x_TOTAL_COUNT); return corsConfiguration;}/*** cross-origin filter ** @ return */@ Bean public CorsFilter corsFilter () {UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource (); source. registerCorsConfiguration ("/**", buildConfig (); // 4 return new CorsFilter (source );}}

22.16index.html

<! DOCTYPE html> 3. Method 3: compile a Filter
Package com. cci. market. common. filter; import java. io. IOException; import javax. servlet. filter; import javax. servlet. filterChain; import javax. servlet. filterConfig; import javax. servlet. servletException; import javax. servlet. servletRequest; import javax. servlet. servletResponse; import javax. servlet. http. httpServletResponse; import org. springframework. stereotype. component;/*** handle cross-origin issues * @ author MR. ZHENG * @ date attributes **/@ Componentpublic class OriginFilter implements Filter {@ Override public void init (FilterConfig filterConfig) throws ServletException {} @ Override public void doFilter (ServletRequest req, res, filterChain chain) throws IOException, ServletException {HttpServletResponse response = (HttpServletResponse) res; response. setHeader ("Access-Control-Allow-Origin", "*"); response. setHeader ("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT"); response. setHeader ("Access-Control-Max-Age", "3600"); response. setHeader ("Access-Control-Allow-Headers", "x-requested-with"); chain. doFilter (req, res) ;}@ Override public void destroy () {// TODO Auto-generated method stub }}
Iv. Nginx cross-origin Configuration

Nginx cross-origin is also relatively simple, just add the following configuration.

location / {    proxy_pass http://localhost:8080;    if ($request_method = 'OPTIONS') {        add_header 'Access-Control-Allow-Origin' '*';        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Token';        add_header 'Access-Control-Max-Age' 1728000;        add_header 'Content-Type' 'text/plain; charset=utf-8';        add_header 'Content-Length' 0;        return 204;    }    if ($request_method = 'POST') {        add_header 'Access-Control-Allow-Origin' '*';        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Token';        add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Token';    }    if ($request_method = 'GET') {        add_header 'Access-Control-Allow-Origin' '*';        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Token';        add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Token';    }}

Here: add_header 'access-Control-Expose-headers' must be added with the header in your request. For example, the "Token" in this example is actually sent from the front end to the backend. If you cannot remember it, the browser debugger will provide a detailed description.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.