信息发布→ 登录 注册 退出

前端JS怎样调用SpringBootActuator_JS调用SpringBootActuator的详细教程

发布时间:2025-11-13

点击量:
前端调用Spring Boot Actuator需先启用端点并配置CORS。1. 引入actuator依赖并在application.yml中暴露health、info等端点;2. 通过WebMvcConfigurer配置允许前端域名访问/actuator/**路径;3. 前端使用fetch请求如/actuator/health获取数据;4. 生产环境应限制敏感端点,结合Spring Security添加认证,避免直接暴露env、shutdown等高危接口。

前端 JavaScript 调用 Spring Boot Actuator 接口是监控和管理后端应用的常用方式。但需要注意的是,Actuator 默认出于安全考虑会限制外部访问敏感端点。要让前端 JS 成功调用,需正确配置后端并处理跨域、权限等问题。

1. 启用并配置 Spring Boot Actuator 端点

Spring Boot 项目中引入 actuator 依赖,并开放必要的端点:



    org.springframework.boot
    spring-boot-starter-actuator

application.yml 中配置可访问的端点:

management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics,env,beans
  endpoint:
    health:
      show-details: always

上述配置暴露了常用的几个端点,如 healthinfometrics 等,并允许显示健康详情。

2. 处理跨域(CORS)以便前端调用

前端 JS 运行在浏览器中,若与后端不同源,必须开启 CORS 支持。创建一个配置类:

@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
public class ActuatorWebConfig {
@Bean
public WebMvcConfigurer webMvcConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/actuator/**")
                    .allowedOrigins("http://localhost:3000") // 允许前端域名
                    .allowedMethods("GET")
                    .allowedHeaders("*");
        }
    };
}

}

这里只允许 GET 方法访问 /actuator/** 路径,可根据实际部署修改 allowedOrigins。

3. 前端使用 JavaScript 调用 Actuator 接口

假设前端运行在 http://localhost:3000,使用 fetch 调用健康接口:

async function getHealth() {
  try {
    const response = await fetch('http://localhost:8080/actuator/health');
    const data = await response.json();
    console.log('服务健康状态:', data);
    // 输出示例: { status: "UP" }
  } catch (error) {
    console.error('调用失败:', error);
  }
}

// 页面加载时调用 getHealth();

其他可用端点示例:

  • /actuator/info:获取应用信息
  • /actuator/metrics:获取指标列表
  • /actuator/metrics/jvm.memory.used:获取具体指标数据
  • /actuator/env:查看环境变量

4. 安全建议与生产注意事项

直接暴露 Actuator 端点有安全风险,尤其在生产环境:

  • 不要暴露 shutdownenv 等高危端点
  • 建议通过反向代理(如 Nginx)或网关(如 Spring Cloud Gateway)限制访问
  • 为敏感端点添加身份验证(如 Spring Security),例如:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(authz -youjiankuohaophpcn authz
            .requestMatchers("/actuator/health", "/actuator/info").permitAll()
            .requestMatchers("/actuator/**").hasRole("ADMIN")
            .anyRequest().permitAll()
        )
        .csrf().disable();
    return http.build();
}

}

此时前端调用受保护端点需携带认证信息(如 JWT 或 Session Cookie)。

基本上就这些。只要后端开放了端点并配置好 CORS,前端 JS 就能顺利调用 Actuator 获取系统状态。不复杂但容易忽略安全细节。

标签:# javascript  # java  # js  # 前端  # json  # nginx  # cookie  # 浏览器  # app  
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!