Express-Gateway配置后无法代理访问Node.js服务接口问题求助
问题原因
当前配置存在两个核心问题:
apiEndpoints配置的路径仅匹配/user单个路径,无法匹配/user/companies_getAll这类带后缀的子路径- 网关代理转发时会把完整请求路径透传给后端服务,也就是访问网关的
/user/companies_getAll会被转发到http://localhost:8001/user/companies_getAll,但你的后端接口实际部署在根路径的/companies_getAll,路径不匹配导致404。
解决方案
按照以下步骤修改Express Gateway的配置YAML文件:
- 调整
apiEndpoints的路径规则,匹配所有/user开头的请求 - 新增
rewrite策略,转发时移除路径前缀/user
修改后的完整配置如下:
http: port: 8080 admin: port: 9876 host: localhost apiEndpoints: api: host: localhost paths: '/user*' # 匹配所有/user开头的路径 serviceEndpoints: user: url: 'http://localhost:8001' policies: - basic-auth - cors - expression - key-auth - log - oauth2 - proxy - rate-limit - rewrite pipelines: default: apiEndpoints: - api policies: - rewrite: # 新增rewrite规则,移除/user前缀 - action: regexp: /user/?(.*) replace: /$1 - proxy: - action: serviceEndpoint: user changeOrigin: true
验证方法
修改配置重启Express Gateway后,访问http://localhost:8080/user/companies_getAll即可正常获取数据,和直接访问后端http://localhost:8001/companies_getAll效果一致。
内容的提问来源于stack exchange,提问作者UAL100
相关产品推荐
相关产品推荐

