【问题标题】:Connection refused when using cross origin使用跨域时连接被拒绝
【发布时间】:2019-07-29 12:13:02
【问题描述】:

我正在使用 Angular 和 spring-boot。 当我想在本地主机之外调用 api 我给了我一个连接被拒绝的错误。

角度服务:

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 应用:

@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);
}
 }

从 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);
    }
}

【问题讨论】:

  • 检查this1是否有帮助。
  • 我的代码是这样的。对 localhost 来说是正确的,但在外面它是错误的
  • 您使用的是 Spring Security 吗?在这种情况下,请在您的问题中包含您的 Spring Security 配置
  • 不,我不使用它
  • 请说明您使用的是哪个 Spring Boot 版本?并且您没有在您的问题中使用 Spring Boot,因为根据它设置 CORS 有不同的方法。

标签: java spring apache spring-boot


【解决方案1】:

请把这个改成config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));

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

【讨论】:

    【解决方案2】:

    删除 setAllowedOrigins 方法并重试。设置和空列表可能是您禁止所有请求离开您的服务器

    【讨论】:

    • 我这样做了,但原因是错误:CORS 标头“Access-Control-Allow-Origin”丢失
    • 当在localhost表单angular外调用api时,angular配置了正确的url而不是localhost?
    • 这是什么?请解释一下。
    • 我询问了 Angular 服务的 url(主机和端口)是否正确。如果是 localhost 并在部署 webapp 时在主机外部执行 angular 服务可能是一个原因,因为您收到连接被拒绝错误。
    猜你喜欢
    • 2019-12-11
    • 2017-08-08
    • 2017-05-18
    • 2019-12-28
    • 2016-04-06
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多