angularspring-bootcorsstackblitz

Cors error between spring boot and angular


I'm have tried to connect spring boot run local in vs code with angular in stackblitz,it keeps showing the status pending and later on net::error

springboot: v3.3.1 angular 17

the url for backend is : http://localhost:8080

and for stackblitz: https://stackblitzstartersf3qupm-d2jk--4200--dc4d7514.local-credentialless.webcontainer.io/

I declared a WebConfig file

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }

}

and in run file

@SpringBootApplication
@ComponentScan(basePackages = "com.example.novelWebsite", basePackageClasses = WebConfig.class) // Add CorsConfig
public class NovelWebsiteApplication {

    public static void main(String[] args) {
        SpringApplication.run(NovelWebsiteApplication.class, args);
    }

}

i also tried the approach of declare in controller but still failed

@RestController
// @CrossOrigin(origins = "https://stackblitzstartersf3qupm-d2jk--4200--dc4d7514.local-credentialless.webcontainer.io/")
public class HelloController {

    @GetMapping("/")
    // @CrossOrigin(origins = "https://stackblitzstartersf3qupm-d2jk--4200--dc4d7514.local-credentialless.webcontainer.io")
    public String index() {
        return "Greetings from Spring Boot!";
    }

}

in main.ts i added

bootstrapApplication(App, {
providers: \[provideAnimationsAsync(),
provideRouter(routes),
provideHttpClient()\]
});

i created proxy.conf.json file

{   "api": "http://localhost:8080",
    "secure": false, 
    "changeOrigin": true }

and put it in angular.json

"serve": {           
     "builder": "@angular-devkit/build-angular:dev-server",           
     "configurations": {             
            "development": {               
                   "buildTarget": "demo:build:development",               
                  ** "proxyConfig": "proxy.conf.json"  **           
            },             
            "production": {               
                   "buildTarget": "demo:build:production"             
            }           
      },           
      "defaultConfiguration": "development"         }       },

here is the service code

export class HelloService {

    private apiURL = 'http://localhost:8080'; // Replace with your Spring Boot backend URL

    constructor(private http: HttpClient) {}

    getGreetings(): Observable\<string\> {
       return this.http.get\<string\>(`${this.apiURL}`);
    }
}

and the component code that received it

ngOnInit() {     
      this.helloService.getGreetings().subscribe({       
         next: (response: string) => {         
             this.responseText = response;       
         },       
         error: (err) => {         
             console.error('Error fetching greetings:', err);       
         }     
      });   
}

and show in html

{{responseText}}

it returned in

Error fetching data: HttpErrorResponse {headers: _HttpHeaders, status: 0, statusText: 'Unknown Error', url: 'http://localhost:8080', ok: false, …}

in network tab it showed status pending for it

I'm have tried to fix it but no good,i would appreciate any help,thank you


Solution

  • I tried another approach instead of having a local backend and a public frontend. I made the backend public too by using ngrok, and it worked. Remember to remove the proxy configuration in Angular