Frontend Development 8 min read

Mastering CORS: 6 Practical Solutions for Frontend‑Backend Integration

This article explains why browsers enforce same‑origin policy, how cross‑origin requests affect front‑end and back‑end communication, and presents six common solutions—including JSONP, Spring @CrossOrigin, WebMvcConfigurer, CorsFilter, Nginx proxy, and other advanced techniques—complete with code examples.

Lobster Programming
Lobster Programming
Lobster Programming
Mastering CORS: 6 Practical Solutions for Frontend‑Backend Integration

In modern projects that separate front‑end and back‑end and use different ports, cross‑origin requests are inevitable. This article first clarifies that cross‑origin issues only occur on the front‑end due to the browser's same‑origin policy, which restricts interactions between different protocol‑domain‑port combinations.

Same‑origin means identical protocol, domain, and port. When the front‑end and back‑end are on different origins, browsers block the request and display an error.

1. JSONP Solution

JSONP leverages the <script> tag, which is not subject to same‑origin restrictions. The front‑end sends a request with a callback parameter, and the back‑end returns JavaScript that invokes the callback.

<code>----------------------Front‑end Code-----------------------
<script>
  $.ajax({
    url: "http://localhost:8080/longxia/biancheng",
    dataType: "jsonp",
    type: "get",
    success: function(data) {
      console.log(data);
    }
  });
</script>
----------------------Back‑end Code-----------------------
@RestController
@RequestMapping("/longxia")
public class CrossController {
    @GetMapping("/biancheng")
    public JSONPObject getData(String callback) {
        System.out.println("龙虾编程");
        return new JSONPObject(callback, "successData");
    }
}
</code>

JSONP works in all browsers but only supports GET requests and has security concerns, so it is rarely used today.

2. CORS with @CrossOrigin Annotation

<code>----------------------Front‑end Code-----------------------
<script>
  $.ajax({
    url: "http://localhost:8080/longxia/cross",
    type: "get",
    success: function(data) {
      console.log(data);
    }
  });
</script>
----------------------Back‑end Code-----------------------
@RestController
@RequestMapping("/longxia")
public class CrossController {
    @GetMapping("/cross")
    @CrossOrigin()
    public String cross() {
        System.out.println("龙虾编程");
        return "successData";
    }
}
</code>

Adding @CrossOrigin to a controller method enables cross‑origin access for that specific endpoint.

3. CORS via WebMvcConfigurer

<code>@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/longxia/*")
                .allowedOrigins("http://localhost:8080")
                .allowedMethods("GET", "POST", "DELETE");
    }
}
</code>

This configuration allows a group of endpoints to share the same CORS settings without annotating each method.

4. CORS via CorsFilter Bean

<code>@Bean
public CorsFilter corsFilter() {
    // 1. Create CORS configuration
    CorsConfiguration config = new CorsConfiguration();
    config.addAllowedOrigin("*");
    config.setAllowCredentials(true);
    config.addAllowedMethod("*");
    config.addAllowedHeader("*");
    config.addExposedHeader("*");
    // 2. Register configuration for all paths
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    // 3. Return the filter
    return new CorsFilter(source);
}
</code>

Using a CorsFilter bean configures CORS globally for the entire application.

5. Nginx Proxy Solution

When the browser accesses longxia.com and the AJAX request targets longxia.com/longxia , the request first reaches Nginx, which forwards it to the back‑end server. Because the proxy operates at the server level, the front‑end does not encounter a cross‑origin error.

<code>server {
  listen 80;
  server_name longxia.com;
}

location / {
  root html;
  index index.html index.htm;
}

location /longxia {
  proxy_pass http://longxia2.com/longxia;
}
</code>

This method is recommended because it avoids code changes on either side.

6. Other Techniques

Additional approaches include WebSocket, window.postMessage , document.domain , iframe communication, window.location.hash , and window.name . Interested readers can explore these alternatives further.

Summary

Cross‑origin is a browser security mechanism, but real projects often need to enable cross‑origin access. It only occurs between front‑end and back‑end on different origins. Common solutions are CORS annotations, global CORS configuration, Nginx proxy, and, historically, JSONP.

backendfrontendSpringCORSCross-OriginNginx
Lobster Programming
Written by

Lobster Programming

Sharing insights on technical analysis and exchange, making life better through technology.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.