我想看看并尝试一下api-gateway是如何工作的,特别是我正在使用的Krakend。从技术上讲,我有一个服务,它只接收一个请求并回复。问题是服务非常简单,当通过api-gateway触发有关端点时,http服务器不会接收来自api-gateway的请求。但是,当我通过浏览器编写确切的url http://localhost:8000/api/v1/users发出get请求时,我会得到响应。基本上,我想要的是,当我向localhost:8099/users (也就是api-gateway )发出get请求时,我希望api网关向用户api发出一个get请求,并查看预期的日志。
这就是我所犯的错误。
错误#01: Get "http://localhost:8000/api/v1/users":拨号TCP127.0.0.1:8000:连接:连接被拒绝
这是我放置配置的krakend.json文件。
{
"version": 2,
"host" : [
"http://localhost:8099"
],
"extra_config": {
"github_com/devopsfaith/krakend-cors": {
"allow_origins": [
"*"
],
"expose_headers": [
"Content-Length"
],
"max_age": "12h",
"allow_methods": [
"GET"
],
"allow_headers": [
"*"
]
}
},
"timeout": "3000ms",
"cache_ttl": "300s",
"output_encoding": "string",
"name": "api-gateway",
"port": 8099,
"read_timeout": "5s",
"idle_timeout": "5s",
"write_timeout": "5s",
"read_header_timeout": "5s",
"endpoints": [
{
"endpoint": "/users",
"method" : "GET",
"backend": [
{
"encoding" : "string",
"url_pattern": "/api/v1/users",
"method": "GET",
"host": [
"http://localhost:8000"
]
}
]
}
]
}这是我的节点js服务器。
const express = require('express')
const app = express()
const cors = require('cors')
var corsOptions = {
origin: 'http://localhost:8099',
methods: "GET, PUT"
}
app.use(cors(corsOptions))
app.get('/api/v1/users', (req, res) => {
console.log('REQUEST => \n')
console.log(req.url)
console.log(req.hostname)
})
app.listen(8000, () => {console.log('server has started on 8000')})因此,当我向address http://localhost:8099/users发出get请求时,日志如下所示:
[GIN] 2021/06/30 - 22:44:05 | 500 | 4.8998ms | 172.17.0.1 | GET "/users"
Error #01: Get "http://localhost:8000/api/v1/users": dial tcp 127.0.0.1:8000: connect: connection refused在这里的Krakend文档中,它说当从后端返回400以上的状态代码时,“我猜”日志是用500代码编写的。
500内部服务器错误默认错误代码,通常,当后端返回任何超过400的状态时
我确实使用了krakend.json文件,并更改了文件的不同部分,但仍然无法工作。
我知道这是一个tcp错误,检查了导致该错误的原因。端口可能会崩溃,这不是真的,因为当我直接向端点http://localhost:8000/api/v1/users发出get请求时,就会得到日志。
发布于 2021-07-09 17:35:43
对于每个服务,docker-compose.yml中声明的容器的名称应该与krakend.json文件中写入的名称相匹配。例如,user-service也应该在krakend.json文件中声明为host字段中的http://user-service:$PORT。
发布于 2022-03-15 03:59:53
更新V3:
如果您使用的是第3版krakend.json文件,那么每个人都可能需要查看这个文件
Using KrakenD with local nodejs server
因为,如果我们将上面的答案与较新版本krakend一起使用,则会引发错误。
https://stackoverflow.com/questions/68202585
复制相似问题