Bootstrap FreeKB - Node.js - Passing events from Express Client to Server
Node.js - Passing events from Express Client to Server

Updated:   |  Node.js articles

Let's say you have an Express client/server application. Check out my articles.

For example, perhaps your server.js file contains something like this.

const express = require("express")
const app = express()
const timestamp = () => Date()

app.get('/', (req, res) => {
  console.log(`${timestamp()} Hello Console`)
  res.send(`${timestamp()} Hello World`)
})

app.listen(8080, () => {
  console.log(`Node.js app is up and running!`);
}

 

And client.js something like this.

console.log("Hello from client");

 

Let's say you want to append the events in client.js to console and/or file log. Let's update server.js with a endpoint that the client will POST requests to.

const express = require("express")
const app = express()
const timestamp = () => Date()

app.get('/', (req, res) => {
  console.log(`${timestamp()} Hello Console`)
  res.send(`${timestamp()} Hello World`)
})

app.post("/log", (req, res) => {
  console.log(req.body.message);
  res.sendStatus(200);
});

app.listen(8080, () => {
  console.log(`Node.js app is up and running!`);
}

 

And then in client.js, POST to the endpoint.

console.log("Hello from client");

fetch("/log", {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ message: 'Is not today a great day' })
});

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 90d090 in the box below so that we can be sure you are a human.