nacos-group / nacos-sdk-nodejs Goto Github PK
View Code? Open in Web Editor NEWnacos node.js sdk client
License: Apache License 2.0
nacos node.js sdk client
License: Apache License 2.0
nacos-config/src/http_agent.ts里面有下列代码
// 获取请求 url
getRequestUrl(currentServer) {
let url;
if (/:/.test(currentServer)) {
url = http://${currentServer}
;
if (this.ssl) {
url = https://${this.currentServer}
; <- 走到这里的时候this.currentServer为undefined,应该采用参数的currentServer。另外this.currentServer一直没有找到设值的地方
}
} else {
url = http://${currentServer}:${this.serverPort}
;
if (this.ssl) {
url = https://${this.currentServer}:${this.serverPort}
; <- 这里有同样问题
}
}
return ${url}/${this.contextPath}
;
}
client.subscribe(serviceName, hosts => {
console.log(hosts);
});
这个console.log根本没有运行。
ps: @czy88840616 什么时候出个midway整合nacos的demo啊?
我使用nodejs测试从远处获取配置,但是获取到的是空的数据
const NacosConfigClient = require('nacos').NacosConfigClient; // js
const configClient = new NacosConfigClient({
serverAddr: '8.130.234.99:8848',
namespace: 'user_src',
});
(async () => {
const result = await configClient.getConfig('test3', 'DEFAULT_GROUP');
console.log(result, '结果');
// 结果是null
})();
如题
版本:nacos 2.0.0
const client = new NacosConfigClient({ serverAddr: NACOS_SERVICE_ADDR, namespace: 'test' }) const content = await configClient.getConfig(DATA_ID, GROUP);
期望:拿到test namespece中dataId=DATA_ID, group = GROUP的nacos配置
结果:null。而且如果dataId跟group来自public就会读取到,即使不写namespace,所以默认namespace是public?
Failed to register with Nacos service in nodejs
bin / www
file, use the registration method of Nacos official websitenpm run start
to startpm2 run pm2. json
. The JSON file contents are as follows{
"script": "./bin/www",
"instances": "1",
"env": {
"NODE_ENV": "development"
},
"env_production": {
"NODE_ENV": "production"
}
}
errored
bin/www
Nodejs中使用nacos服务注册失败
bin/www
文件下,使用nacos官网注册方式npm run start
启动pm2 run pm2.json
,其中json文件内容如下{
"script": "./bin/www",
"instances": "1",
"env": {
"NODE_ENV": "development"
},
"env_production": {
"NODE_ENV": "production"
}
}
期望行为
希望能够像dev启动中一样正常注册服务
Expected behavior
I hope to be able to register the service as normal as in dev startup
v1.1.3版的nacos,服务器默认的namespace是public,目前这个nodejs这个是defalut,是注册不上的,花了一天功夫才调试出问题在这,把下面这两个文件的namespace值改成default才行:
nacos-naming\lib\naming\client.js
nacos-naming\lib\naming\proxy.js
错
const defaultOptions = {
namespace: 'default',
....
};
正确
const defaultOptions = {
namespace: 'public',
....
};
nacos-naming不支持typescript
注册:
'use strict';
const NacosNamingClient = require('nacos').NacosNamingClient;
const logger = console;
const client = new NacosNamingClient({
logger,
serverList: '127.0.0.1:8848', // replace to real nacos serverList
namespace: 'public',
});
(async () => {
await client.ready();
const serviceName = 'controller';
await client.registerInstance(serviceName, {
ip: '2.2.2.2',
port: 8080,
enabled: true,
metadata: {room: '1231231'},
});
})();
发现:
'use strict';
const NacosNamingClient = require('nacos').NacosNamingClient;
const logger = console;
const client = new NacosNamingClient({
logger,
serverList: '127.0.0.1:8848', // replace to real nacos serverList
namespace: 'public',
});
(async () => {
await client.ready();
const serviceName = 'controller';
// subscribe instance
await client.subscribe(serviceName, hosts => {
console.log(hosts);
});
})();
index.js?bed3:161 [WDS] Errors while compiling. Reload prevented.
errors @ index.js?bed3:161
onmessage @ socket.js?57b2:41
EventTarget.dispatchEvent @ sockjs.js?3600:170
eval @ sockjs.js?3600:887
SockJS._transportMessage @ sockjs.js?3600:885
EventEmitter.emit @ sockjs.js?3600:86
WebSocketTransport.ws.onmessage @ sockjs.js?3600:2961
index.js?bed3:167 ./node_modules/nacos-naming/lib/naming/host_reactor.js
Module parse failed: Can not use 'await' as identifier inside an async function (191:17)
You may need an appropriate loader to handle this file type.
| } else if (this._updatingSet.has(key)) {
| // await updating
| await this.await(${key}_changed
);
| }
| this._scheduleUpdateIfAbsent(serviceName, clusters);
@ ./node_modules/nacos-naming/lib/naming/client.js 26:20-45
@ ./node_modules/nacos-naming/index.js
@ ./node_modules/nacos/dist/index.js
@ ./src/common/nacos/config_service.js
@ ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/pages/system/main/music.vue
@ ./src/pages/system/main/music.vue
@ ./src/router/index.js
@ ./src/main.js
@ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/main.js
获取的配置为什么是string,能否序列化成对象
node.js怎么调用其他服务提供的 gRpc 接口?
Hi there,
Is there any API in sdk supporting fuzzy query for dataId?
Just Like dataId=*app_id
in HTTP request.
Thanks.
在eggjs中如何以provider形式创建nacos
配置里面只写了如何连接阿里云的acm服务,我本地搭建的nacos如何连接呢?看官方的接口里面也没有类似参数呢.
accessKey: '***************',
secretKey: '***************',
另外k8s部署的nacos开启了鉴权之后,我的web使用帐号密码登录不上了,提示帐号密码错误,关闭NACOS_AUTH_ENABLE=false之后可以正常登录了,这是为啥呢?
getConfig方法无法获取非public空间下的配置
正确的获取请求
curl http://some.nacos.instance/nacos/v1/cs/configs?dataId=TEST_CONFIG_ITEM&group=LOCAL&tenant=1243f842-fa03-4ef8-b226-5ba55a79052c
文档
追踪了一下源码没有地方提供这个参数的支持
Nacos version: 1.1.4
nacos-nodejs-sdk version: 2.0.0
Nodejs version: 14.15.5
npm version: 6.14.11
OS version: centos 7.6
logger.info('Connecting Nacos config client...')
const configClient = new NacosConfigClient({
serverAddr: config.nacos.serverAddr,
namespace: config.nacos.namespace
});
const content = await configClient.getConfig('-', '-');
// let doc = yaml.load(content)
let doc = JSON.parse(content)
appConfig.set(doc)
output:
2021-02-23 18:28:39,119 WARN 2197 nodejs.ResponseTimeoutError: register to channel: DiamondClient@undefined failed, will retry after 3s, Server no response in 3000ms, address#127.0.0.1:7777
at Timeout._onTimeout (/app/data/${project}/node_modules/tcp-base/lib/base.js:225:21)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
socketMeta: {"id":2,"dataLength":91,"bufferSize1":0,"bufferSize2":0,"startTime":1614076116118,"endTime":1614076116118,"writeSuccess":true}
name: "ResponseTimeoutError"
pid: 2197
I tried curl command on server
curl -G -d 'tenant=${namespace}' -d 'dataId=${dataid}' -d 'group=${group}' http:/${host}/nacos/v1/cs/configs
which returns the correct configuration stored in nacos.
In addition, the same code works in win10 and Java client with same configuration can get nacos config successfully.
用publishSingle更新配置,type无法设置,options { type : xxx } 并不支持
standalone模式启动的,应该没有serverlist的接口。
log如下
cluster-client [ClusterClient:[email protected]:8848] init cluster client, try to seize the leader on port:7777 +0ms
cluster-client:server listen 7777 success +0ms
diamond-client:snapshot 0.7743671956236662 +0ms
cluster-client [ClusterClient:[email protected]:8848] has seized port 7777, and serves as leader client. +8ms
nacos:9342:ins-496:client_worker client worker start +0ms
nacos:9342:ins-496:client_worker calling getConfig, dataId: test, group: DEFAULT_GROUP +1ms
urllib Request#1 GET http://127.0.0.1:8848/nacos/serverlist with headers {"User-Agent":"node-urllib/2.31.3 Node.js/10.13.0 (Linux 4.19; x64)"}, options.path: /nacos/serverlist +0ms
urllib ConnectTimeout: 6000, ResponseTimeout: 6000 +1ms
urllib Connect timer ticking, timeout: 6000 +2ms
urllib Response timer ticking, timeout: 6000 +3ms
urllib Request#1 http://127.0.0.1:8848/nacos/serverlist new socket connected +0ms
urllib Request#1 http://127.0.0.1:8848/nacos/serverlist req response
event emit: status 404, headers: {"content-type":"application/json;charset=UTF-8","transfer-encoding":"chunked","date":"Tue, 11 Dec 2018 20:54:41 GMT"} +109ms
urllib Request#1 http://127.0.0.1:8848/nacos/serverlist: res data
event emit, size 137 +1ms
urllib Request#1 http://127.0.0.1:8848/nacos/serverlist: res end
event emit, total size 137, _dumped: false +0ms
urllib [118ms] done, 137 bytes HTTP 404 GET 127.0.0.1 /nacos/serverlist, keepAliveSocket: false, timing: null, socketHandledRequests: 1, socketHandledResponses: 1 +1ms
[Wed Dec 12 2018 04:54:41 GMT+0800 (China Standard Time)][pid: 9342][NacosConfigClient] NacosServerResponseError: [Nacos#ServerListManager] request url: http://127.0.0.1:8848/nacos/serverlist failed with statusCode: 404
Error Stack:
NacosServerResponseError: [Nacos#ServerListManager] request url: http://127.0.0.1:8848/nacos/serverlist failed with statusCode: 404
at ServerListManager.request (/home/jiangzhuo/Desktop/test-client/node_modules/nacos-config/src/server_list_mgr.ts:126:35)
at process._tickCallback (internal/process/next_tick.js:68:7)
Error Additions:
url: "http://127.0.0.1:8848/nacos/serverlist"
params: {"timeout":6000,"dataType":"text","requestUrls":["http://127.0.0.1:8848/nacos/serverlist"],"maxRedirects":10}
body: "{"timestamp":"2018-12-11T20:54:41.199+0000","status":404,"error":"Not Found","message":"No message available","path":"/nacos/serverlist"}"
nacos nodejs client start for a while, there are may "TIME_WAIT" to nacos servier connections.
直连模式 [Client] options.endpoint is required
问题现象:启动一个依赖nacos监听事件的服务,启动成功后断开网络,40秒后服务进程的CPU使用率飙到100%左右
原因:http_agent中有一个逻辑是某些请求失败场景会一直重试请求,直到默认40秒超时才停止
发现缺少更加安全的通过RAM访问的接口。根据我所知道的情况,通过RAM访问应该比硬编码AK安全。请问一下,您近期是否有相关计划?
1.2.0的nacos server 加了账号密码后怎么都连不上了,node 这边连不上 但是java那边却连得上
2.2.1同时创建2个NacosConfigClient,除了namespace不同,其他参数都是一样的,第二个实例必定报连接失败错误
无法支持namespace,namespaceId为实际注册导致无法。尝试修改注册也无效。
async registerService(serviceName, instance) {
this.logger.info('[NameProxy][REGISTER-SERVICE] registering service: %s with instance:%j', serviceName, instance);
const params = {
namespaceId: '3c239366-d993-489a-afbe-89e53160117f', //自定义命名空间
ip: instance.ip,
port: instance.port + '',
weight: instance.weight + '',
enable: instance.enabled ? 'true' : 'false',
healthy: instance.healthy ? 'true' : 'false',
metadata: JSON.stringify(instance.metadata),
clusterName: instance.clusterName,
serviceName,
};
console.log('registerService:',params);
return await this.reqAPI(Constants.NACOS_URL_INSTANCE, params, 'PUT');
}
官网文档中的open-api跟代码中的编码有差异。
http://${this.nameServerAddr}/${this.contextPath}/${this.clusterName}
;
接口http://ip:port/nacos/serverlist在文档中找不到
是否有支持node6.0及以下版本的包
你好,我在使用这个nacos库,但是发现了一些问题
const configClient = new NacosConfigClient({
serverAddr: '127.0.0.1:50010',
// serverAddr: BR_NACOS_SERVER,
// serverAddr,
namespace: DATAVIEW_NAMESPACE
})
const configGlobalClient = new NacosConfigClient({
// serverAddr: '127.0.0.1:50011',
// serverAddr: BR_NACOS_SERVER,
serverAddr,
namespace: GLOBAL_NAMESPACE
})
// const content = await configClient.getConfig(CONFIG_DATAVIEW_ID, CONFIG_DATAVIEW_GROUP)
// logger.info('======== GET dataview nacos config once =====', content)
configClient.subscribe({
dataId: CONFIG_DATAVIEW_ID,
group: CONFIG_DATAVIEW_GROUP
}, content => {
logger.info('======== GET dataview nacos config =====', content)
})
configGlobalClient.subscribe({
dataId: CONFIG_GLOBAL_ID,
group: CONFIG_GLOBAL_GROUP
}, content => {
logger.info('======== GET global nacos config =====', content)
})
期待结果
:
'======== GET dataview nacos config once ====='
xxx
'======== GET global nacos config ====='
xxx
实际输出
:
'======== GET dataview nacos config once ====='
xxx
'======== GET global nacos config ====='
null
使用中发现,只有前面的对面会输出结果,后面的数据结果是null,有时间请大神帮忙看下这个问题
(node:15631) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token C in JSON at position 2 (address: 127.0.0.1:7777)
at JSON.parse ()
at Function.decode (/root/works/eryipay/node_modules/nacos-config/node_modules/cluster-client/lib/protocol/packet.js:86:26)
at Follower.decode (/root/works/eryipay/node_modules/nacos-config/node_modules/cluster-client/lib/follower.js:68:27)
at Follower._readPacket (/root/works/eryipay/node_modules/tcp-base/lib/base.js:308:25)
at Follower.handleReadable (/root/works/eryipay/node_modules/tcp-base/lib/base.js:374:26)
at Socket.socket.on (/root/works/eryipay/node_modules/tcp-base/lib/base.js:392:40)
at Socket.emit (events.js:182:13)
at emitReadable (_stream_readable.js:534:12)
at onEofChunk (_stream_readable.js:512:7)
at readableAddChunk (_stream_readable.js:232:5)
(node:15631) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)
(node:15631) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
^C
My nacos server has username and password, but I can't find the username
and password
fields in the ClientOptions
interface.
const configClient = new NacosConfigClient({
serverAddr: 'ip',
namespace: 'namesapce',
username: 'username',
password: 'password'
});
Nacos nodejs sdk version: 2.0.0
.
复制 Readme里面的代码,
// index.js
const {NacosConfigClient} = require('nacos'); // js
// for direct mode
const configClient = new NacosConfigClient({
serverAddr: '127.0.0.1:8848',
});
// listen data changed
configClient.subscribe({
dataId: 'test',
group: 'DEFAULT_GROUP',
}, content => {
console.log(content);
});
执行 node index.js
然后报错
[Sun Mar 31 2019 00:20:06 GMT+0800 (GMT+08:00)][pid: 56608][NacosConfigClient] AssertionError [ERR_ASSERTION]: [Client] options.endpoint is required
Error Stack:
AssertionError [ERR_ASSERTION]: [Client] options.endpoint is required
at new DataClient (/Users/xxx/code/demo/node_modules/nacos-config/dist/client.js:31:9)
at Object.createRealClient (/Users/xxx/code/demo/node_modules/cluster-client/lib/index.js:102:22)
at new Leader (/Users/xxx/code/demo/node_modules/cluster-client/lib/leader.js:38:37)
at ClusterClient.[ClusterClient#init] (/Users/xxx/code/demo/node_modules/cluster-client/lib/client.js:88:27)
at process._tickCallback (internal/process/next_tick.js:68:7)
at Function.Module.runMain (internal/modules/cjs/loader.js:744:11)
at startup (internal/bootstrap/node.js:285:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)
Error Additions:
generatedMessage: false
code: "ERR_ASSERTION"
actual: undefined
expected: true
operator: "=="
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.