前端调用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 成功调用,需正确配置后端并处理跨域、权限等问题。
在 Spring Boot 项目中引入 actuator 依赖,并开放必要的端点:
<!-- Maven 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
在 application.yml 中配置可访问的端点:
management:
endpoints:
web:
exposure:
include: health,info,metrics,env,beans
endpoint:
health:
show-details: always
上述配置暴露了常用的几个端点,如 health、info、metrics 等,并允许显示健康详情。
立即学习“前端免费学习笔记(深入)”;
前端 JS 运行在浏览器中,若与后端不同源,必须开启 CORS 支持。创建一个配置类:
@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
public class ActuatorWebConfig {
<pre class='brush:php;toolbar:false;'>@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。
假设前端运行在 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);
}
}
<p>// 页面加载时调用
getHealth();</p>其他可用端点示例:
直接暴露 Actuator 端点有安全风险,尤其在生产环境:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
<pre class='brush:php;toolbar:false;'>@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authz -> authz
.requestMatchers("/actuator/health", "/actuator/info").permitAll()
.requestMatchers("/actuator/**").hasRole("ADMIN")
.anyRequest().permitAll()
)
.csrf().disable();
return http.build();
}}
此时前端调用受保护端点需携带认证信息(如 JWT 或 Session Cookie)。
基本上就这些。只要后端开放了端点并配置好 CORS,前端 JS 就能顺利调用 Actuator 获取系统状态。不复杂但容易忽略安全细节。
以上就是前端JS怎样调用SpringBootActuator_JS调用SpringBootActuator的详细教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号