You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot与Angular JS跨域问题:No 'Access-Control-Allow-Origin'报错求助

Hey there, let's tackle that CORS error you're facing when your AngularJS app tries to fetch data from your Spring Boot REST service. I’ve dealt with this exact issue plenty of times, so here are some concrete, easy-to-implement solutions to add the Access-Control-Allow-Origin header correctly:

1. Use the @CrossOrigin Annotation (Quick Fix)

This is the simplest way to enable CORS for specific controllers or methods. Just add the annotation to your MessagesController class (or individual handler methods) to allow cross-origin requests:

Apply to the entire controller

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;

// Allow all origins (use specific domains in production!)
@CrossOrigin(origins = "*")
@RestController
public class MessagesController {
    // Your GET endpoint (e.g., @GetMapping("/messages"))
    public List<Messages> getAllMessages() {
        // Your business logic here
        return messageService.getAll();
    }
}

Apply to a single method

If you only want to enable CORS for a specific endpoint, add the annotation directly to the method:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;

@RestController
public class MessagesController {

    // Restrict to your AngularJS app's domain (e.g., localhost:8000)
    @CrossOrigin(origins = "http://localhost:8000")
    @GetMapping("/messages")
    public List<Messages> getAllMessages() {
        return messageService.getAll();
    }
}

Note: In production, avoid using * for origins — always specify your actual frontend domain to prevent security risks.

2. Global CORS Configuration (For Entire Application)

If you need CORS enabled across all your REST endpoints, set up a global configuration class. This is cleaner than adding annotations to every controller:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class GlobalCorsConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**") // Apply to all endpoints
                        .allowedOrigins("http://localhost:8000") // Your AngularJS domain
                        .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // Allow common HTTP methods
                        .allowedHeaders("*") // Allow all request headers
                        .allowCredentials(true); // Enable if your app uses cookies/auth tokens
            }
        };
    }
}

3. Custom CORS Filter (Low-Level Control)

If you need more granular control over the CORS headers, create a custom filter that injects the required headers into every response:

Step 1: Create the Filter Class

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CustomCorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        // Allow your AngularJS app's domain
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:8000");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        
        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {}

    @Override
    public void destroy() {}
}

Step 2: Register the Filter in Spring Boot

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FilterRegistrationConfig {

    @Bean
    public FilterRegistrationBean<CustomCorsFilter> corsFilterRegistration() {
        FilterRegistrationBean<CustomCorsFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new CustomCorsFilter());
        registrationBean.addUrlPatterns("/*"); // Apply to all paths
        return registrationBean;
    }
}

Quick Note for AngularJS

If you enabled allowCredentials in your Spring Boot config, make sure to set withCredentials: true in your AngularJS $http request (in your ctrl.js):

// Inside your controller
$http.get('http://your-spring-boot-api-url/messages', { withCredentials: true })
    .then(function(response) {
        // Handle successful response
        $scope.messages = response.data;
    }, function(error) {
        // Handle error
        console.error('Error fetching messages:', error);
    });

Pick the method that best fits your use case — the @CrossOrigin annotation is great for quick tests, while global configuration is better for production apps. After implementing any of these, restart your Spring Boot service and test your AngularJS app again — the CORS error should be gone!

内容的提问来源于stack exchange,提问作者xpioneer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:44:22