I am using from Angular and spring-boot.
When I want to call api outside the localhost
I am giving me a connection refused error.
Angular service:
export class ProfileService {
private baseUrl = 'http://localhost:8090/users';
constructor(private http: HttpClient) {
}
getProfile(id: number): Observable<Object> {
return this.http.get(`${this.baseUrl}` + '/load/' + `${id}`);
}
spring-boot Application:
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.setAllowedOrigins(Collections.singletonList("*"));
config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
userscontroller that get request from angular :
@RestController
@RequestMapping("/users")
public class UsersController {
@Autowired
private IUsersService iUsersService;
@GetMapping("/list/grid")
public Iterable<UsersViewModel> getAllEmployees() {
return Dozer.mapList(iUsersService.getAll(), UsersViewModel.class);
}
@GetMapping("/load/{id}")
public UsersViewModel getUserById(@PathVariable(value = "id") Long userId){
return Dozer.mapClass(iUsersService.findById(userId).get(),UsersViewModel.class);
}
}
2
Answers
Remove the setAllowedOrigins method and try again. Setting and empty list may be you are banning all requests out of your server
Please change this to
config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));
to
config.setAllowedHeaders(Arrays.asList("*"));