前端通过http请求调用springCloud微服务需经API网关,1. 微服务注册至eureka/Nacos并暴露REST接口;2. 网关配置路由规则转发请求;3. 网关配置CORS解决跨域;4. 前端使用fetch/axios调用网关地址;5. 可选JWT认证,请求携带Token。

前端javaScript调用SpringCloud微服务,本质是通过HTTP请求与后端暴露的restful接口通信。由于SpringCloud微服务通常运行在内网或独立服务中,前端不能直接访问,需要通过网关统一暴露接口。以下是具体实现步骤。
1. 微服务注册与暴露API
确保你的微服务已接入SpringCloud生态:
- 使用Eureka、Nacos等作为注册中心,微服务启动后自动注册。
- 每个微服务提供标准的REST接口(如使用spring boot + @RestController)。
- 例如:用户服务提供GET /api/users/{id}接口返回用户信息。
2. 配置API网关(如spring cloud gateway)
前端不直接调用具体微服务,而是通过API网关转发请求:
- 搭建Spring Cloud Gateway服务,配置路由规则。
- 例如:将/user-service/** 转发到用户微服务。
- 这样外部请求只需访问http://gateway-host/user-service/api/users/1即可。
3. 解决跨域问题(CORS)
前端运行在浏览器,常见于localhost:3000或nginx部署地址,与网关域名不同,必须处理跨域:
立即学习“前端免费学习笔记(深入)”;
- 在网关或具体微服务中添加CORS配置。
- 示例代码(Spring Boot):
<font color="#555555">@Configuration public class CorsConfig { @Bean public CorsWebFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("http://localhost:8080"); // 前端地址 config.addAllowedMethod("*"); config.addAllowedHeader("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return new CorsWebFilter(source); } }</font>
4. 前端js发起HTTP请求
使用原生fetch或axios等库调用网关暴露的接口:
- 确保请求地址指向API网关。
- 示例(使用fetch):
<font color="#555555">fetch('http://your-gateway-domain/user-service/api/users/1') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));</font>
5. 认证与权限控制(可选但推荐)
生产环境中需加入安全机制:
- 使用JWT或OAuth2,在请求头中携带token。
- 前端登录后获取token,并在每次请求中添加:
<font color="#555555">fetch('/user-service/api/users/1', { headers: { 'Authorization': 'Bearer your-jwt-token' } })</font>
- 网关或微服务验证token合法性。
基本上就这些。只要网关配置正确、跨域解决、接口可用,前端JS就能顺利调用SpringCloud微服务。关键是前后端分离架构下,通过API网关统一入口,实现安全、可维护的通信。