简体   繁体   中英

Connection refused when using cross origin

在此处输入图片说明 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);
    }
}

Please change this to config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));

to

config.setAllowedHeaders(Arrays.asList("*"));

Remove the setAllowedOrigins method and try again. Setting and empty list may be you are banning all requests out of your server

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM