Node.js - Passing events from Express Client to Server

by
Jeremy Canfield |
Updated: November 25 2024
| Node.js articles
Let's say you have an Express client/server application. Check out my articles.
- Node.js - Getting Started with Client Server Express on Docker
- Node.js - Getting Started with Client Server on Docker
- Node.js - Getting Started with Client Server on Linux using CommonJS
- Node.js - Getting Started with Client Server on Linux using ES Module
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