Categories
JavaScript Answers

How to return a complex JSON response with Node.js?

To return a complex JSON response with Node.js, we call the res.json method.

For instance, we write

res.json({ msgId: msg.fileName });

to call res.json to return the object as the response body.

Categories
JavaScript Answers

How to update all clients using Socket.io and Node?

To update all clients using Socket.io and Node, we call the emit method.

For instance, we run

io.sockets.emit("users_count", clients);

to call emit to emit the users_count event with the clients object as the payload.

Categories
JavaScript Answers

How to run Node.js on port 80?

To run Node.js on port 80, we route port 80 to the local port the Node app is running on.

For instance, we run

sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080

to run iptables to add a route entry to route port 80 to our Node app running on port 8080.

Categories
JavaScript Answers

How to get connection status on Socket.io client with JavaScript?

To get connection status on Socket.io client with JavaScript, we use the socket.connected property.

For instance, we write

const socket = io.connect();
console.log("check 1", socket.connected);
socket.on("connect", () => {
  console.log("check 2", socket.connected);
});

to get the connection status from the socket.connected boolean variable.

If it’s true, then the client is connected.

Categories
JavaScript Answers

How to fix ECONNREFUSED for Postgres on Node.js with error Docker?

To fix ECONNREFUSED for Postgres on Node.js with error Docker, we make sure the connection string is correct.

For instance, we write

DATABASE_URL: postgres://username:pgpassword@db:5432/mydatabase

to set the DATABASE_URL environment variable to a connection string for postgres.

We add the username and password with the database name in the string.