简体   繁体   中英

Nodejs Express API with NATS?

I am trying to build a REST API for my frontend app using nodejs + express + nats. I have a nats-server running in my terminal.

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.

I found a similar project on 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:

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

Nats Connection documentation:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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