I am interested in creating (for testing purposes) a fake client that mimics a browser accessing a route in a Node.js HTTP server. In the minimal example below, I am able to point an actual browser to http://localhost:3099/register and see "Hello World". Where do I find "Hello World" when using socket.io-client to access the same route?
const express = require('express');
const http = require('http');
const server = require("socket.io").Server;
const ioclient = require("socket.io-client").io;
const app = express();
const mywebserver = http.createServer(app).listen(3099, () => {
console.log("listening on port 3099");
});
const io = new server(mywebserver);
app.get('/register', (req,res) => {
res.writeHead(200, {"Content-Type" : "text/plain"});
res.write('Hello World');
res.end();
});
const client = ioclient("http://localhost:3099/register", {autoConnect: true});
console.log(client);
The last line spits out the socket object, but that is clearly not helpful. I've tried adding an on("connect")
handler, but so far have not been able to figure out how to access the "Hello World" string sent by the server within the handler.
install package for api calling, I have used Axios (npm install axios).
Make an HTTP request to the /register endpoint.
add this code :
client.on("connect", async () => {
console.log("Socket connected");
try {
const response = await axios.get('http://localhost:3099/register');
console.log(response.data);
} catch (error) {
console.log("Error accessing /register endpoint:",error.message);
}
});