简体   繁体   English

带有 NATS 的 Nodejs Express API?

[英]Nodejs Express API with NATS?

I am trying to build a REST API for my frontend app using nodejs + express + nats.我正在尝试使用 nodejs + express + nats 为我的前端应用程序构建 REST API。 I have a nats-server running in my terminal.我的终端中有一个 nats-server 正在运行。

This is my test code:这是我的测试代码:

var express = require("express");
var app = express();
const NATS = require('nats');
const nc = NATS.connect();
nc.on('connect', () => {
    console.log('connected');
})

nc.publish('foo', 'Hello World!');

app.get('/', (req,res) => {
    nc.subscribe('foo', function (msg) {
        res.send(msg)
    });
});

app.listen(3000, () => {
 console.log("Server running on port 3000");
});

After running test code, localhost:3000 cannot be reached.运行测试代码后,无法访问localhost:3000。

I found a similar project on github: https://github.com/georgehaidar/poc-express-nats/blob/master/api.js .我在 github 上发现了一个类似的项目: https : //github.com/georgehaidar/poc-express-nats/blob/master/api.js

I cant seem to find my error.我似乎找不到我的错误。

Can anyone plz help me figure out what im doin wrong?谁能帮我弄清楚我做错了什么?

Thank you in advance.先感谢您。

It looks like you've not provided the nats.connect() method with a hostname like the original author does:看起来您没有像原作者那样提供带有主机名的 nats.connect() 方法:

const nats = require('nats').connect({'servers': ['nats://nats:4222']})

Nats Connection documentation: Nats 连接文档:

https://docs.nats.io/developing-with-nats/connecting/specific_server https://docs.nats.io/developing-with-nats/connecting/specific_server

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM