Vue.js frontend to Spring backend: Fixing CORS issues?

Hey everyone! I’m stuck with a CORS problem in my app. My Vue.js frontend (on localhost:8081) can’t fetch data from my Spring backend (on localhost:8080).

I’ve tried adding @CrossOrigin(origins = "http://localhost:8081") to my backend controller, but no luck. Still getting the same CORS error. Here’s a simplified version of my setup:

// Frontend (Vue.js)
export default {
  data() {
    return { items: [] }
  },
  mounted() {
    fetch('http://localhost:8080/getItems')
      .then(res => res.json())
      .then(data => this.items = data)
  }
}
// Backend (Spring)
@RestController
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class ItemController {
    @GetMapping("/getItems")
    public List<Item> getItems() {
        return itemService.getAllItems();
    }
}

Any ideas on how to fix this? I’m really confused about why the CORS setup isn’t working. Thanks in advance for any help!

have u tried checking the network tab in devtools? sometimes the real issue hides there. also, maybe ur backend’s throwing an error before CORS kicks in? try adding some logging to ur Spring controller to see if the request even reaches it. and double-check ur vue fetch - maybe there’s a typo in the URL? just brainstorming here :thinking:

I’ve encountered similar CORS issues in my projects. One solution that worked for me was implementing a global CORS configuration in Spring. Instead of using @CrossOrigin annotations, try creating a separate configuration class:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8081")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}

This approach ensures consistent CORS settings across your entire application. Also, double-check your network requests in the browser’s developer tools. Sometimes, preflight OPTIONS requests can reveal additional CORS-related issues not immediately apparent in the main request.

hey mate, have u tried using a proxy in ur vue app? it can bypass CORS probs. add this to ur vue.config.js:

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true
      }
    }
  }
}

ten just fetch from ‘/api/getItems’ in ur component. worked for me!