Is it possible to use console.log() in the backend (I am using express) to output things in the frontend.
for example:
const express = require('express');
const app = express();
client.console.log('Hi');
How would I do it?
Thanks.
There is no built-in support for a server to cause something to show in the client console. I'm not sure what the actual use case for that is since the console is typically a debugging aid, not an actual end-user thing.
In any case, if you want to do that, you would have to have cooperating code on both the client and the server and then how that code works depends upon the context in which you want to put the info in the console.
From a page load
From a page load, the server could embed a small script in the page that would output into the browser console when the page loads and runs.
From an Ajax call
Here, you could include a property in some returned JSON that contains the desired console message and then the client code making the ajax call would have to grab that property and call console.log() with it.
From any random time on the server
If you're not in the context of an existing request from the browser or web page Javascript (as in the previous two points), then you would need some push channel connected between the web page and the server such as a webSocket connection, a socket.io connection or a SSE connection. Then, you could send a message to the client and the client would need some code listening for those incoming messages and then display them in the local console upon receiving them.
try it:
The 'send' method of 'res' object of Express, is one of so many ways to send a response to client in the request event.
const express = require('express')
const app = express()
app.get('/test', (req, res) => {
return res.send('Hello world!')
})
There is no support as jfriend00 said, but there is a way to go around this.
So lets say the user requests /test
You want to displayin his console Hello World
So you do:
const express = require('express')
const app = express()
app.get('/test', (req, res) => {
return res.send('<script>console.log(Hello world!)</script>')
})
And that acts as a full client console log. There ya go. (Single Time)
Or setup socket.io as jfriend said in his post if you want to constantly post console messages (multiple times).
Related
Many times I have created apps with express where I just spin up a server at a port and then on the client side do all the stuff. whether that be fetching with fetch/axios, rendering data, and even changing routes (react-router). I have never hugely explored node or the server part, until now....hopefully.
I get what it's doing partially. in terms of
app.get('/', (req, res) => res.send('Hello World!'))
this just sends the response to the browser window. and I have even managed to do this:
app.listen(port, () => {
console.log("Listening");
fetch(url, {
}).then((res => res.json()))
.then((json => console.log('json')))
.catch(() => {
console.log("bbb");
});
});
and this logs all the data into the sever window. however, I have a couple of questions
should I be doing this in the server or the client? whats the advantage?
secondly, once I have this data, how can I send it to the client? i.e. a react component
also, I cant seem to copy this code and get it work inside app.get()? am I doing it wrong? maybe I have misunderstood there
I understood more than questions, an answer to all would be great but I would just like to have some more knowledge on what goes inside express and the server
should I be doing this in the server or the client? whats the advantage?
You have to consider the followig things when requesting another server:
Serverside:
you can share the data to multiple clients
you can keep algorithms / secrets private
you probably have a better bandwith than your clients, so you can load big chunks of data and then only send the neccessary data to the client
Client:
Does not consume your servers ressources
secondly, once I have this data, how can I send it to the client? i.e. a react component
You can use AJAX, websockets (http://socket.io) or you have to use redirects.
also, I cant seem to copy this code and get it work inside app.get()?
If you expected to see the data at the client, you have to res.json(json).
I am trying to run a NodeJS cron at a set interval using cron-job.org, but they don't have any documentation about how to actually run the script.
Basically the service visits a URL that you provide at a set interval, but I am specifically confused about what kind of code I can put on the endpoint (specifically what type of code will actually run). Can someone provide an example of what I would put at the endpoint URL?
You can do something really simple using either the HTTP module in Node.js or the popular Express module. Using express you can do something really simple like:
var express = require('express');
var app = express();
app.get("/test", function(req, res, next){
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ status: 'OK', timeStamp: new Date().toISOString() }));
});
console.log('Express listening.. on 3000');
app.listen(3000);
You can really run anything you like in the /test endpoint, though when it's being called from cron-job.org they'll probably stop if you keep throwing back 400 errors at them or the script takes really long to execute.
You'd call this using the url
http://yourdomain:3000/test
And of course you might well want to change the port number and path!
cron-job.org only allows you to call an endpoint at a set time interval.
If you want to have some code run at a set interval without worrying about HTTP server, deploying, etc... Check out services like chunk.run
Here's an example code:
https://chunk.run/c/scheduled-run-example
Then you can just select the trigger "Scheduled" like so:
My application is a web interface to monitor changes on "objects" processed by the pc and in particular when they get over a particular threshold.
The Node Js server runs on the same pc and has the only use of displaying data on a table, refreshing it when one of them reached a given threshold.
At that point the program that calculates the "objects" opens a socket to the Node Js server and sends the json data.
My issue is to reload the page on the user browser to diplay the new resoults without having the user to manually hit the browser refresh button.
For the server I used the express, express-ejs-layouts and body-parser modules.
This is my server code:
// require our dependencies
var express = require('express');
var expressLayouts = require('express-ejs-layouts');
var bodyParser = require('body-parser');
var app = express();
var port = 3000;
// use ejs and express layouts
app.set('view engine', 'ejs');
app.use(expressLayouts);
// use body parser
app.use(bodyParser.json({extended : true}));
// route our app
var router = require('./app/routes');
app.use('/', router);
// set static files (css and images, etc) location
app.use(express.static(__dirname + '/public'));
// start the server
app.listen(port, function() {
console.log('app started');
});
Leaving aside page estetics (css,images, layouts) the core of the server,
serving GET and POST requests is on the routes.js file that, on GET requests renders the pages passing the JSON data to the javascript page containing the table and on POST requests saves the JSON passed by my "objects" calculator.
This is the routes.js code:
// require express
var express = require('express');
var path = require('path');
// create our router object
var router = express.Router();
// export our router
module.exports = router;
router.post("/", function(request, response) {
global.exportage = request.body;
});
// route for our homepage
router.get('/displayobj', function(req, res) {
//res.send(global.exportage);
res.render('pages/displayobj',{data:global.exportage});
});
How you can see I'm using a quite horrible global variable to pass data but I wanted to keep it as simple as possible.
How could I force the reload on the user browser when a new JSON is received?
I tried using location.reload(true) but I get an error during execution saying: "location is not defined".
The problem, in my opinion, is that the server satisfies the GET request issued by the browser and nothing else happens cause the communication is already completed. I would like not to refresh the page with a fixed interval of time but using the new JSON as triggering event (edited after reading comments).
You cannot do real time communication from server to client with simple HTTP requests. Consider using either long polling or websockets.
The simplest solution for you is to use a library like Socket.io that handles it. When the content need to be refreshed, send an event to the client and then either refresh using window.location.reload() or update the content with the DOM API.
I created simple app to start with socket.io, but when I run it, Chrome(tested in other browsers, result same) eats all of my CPU and makes many requests:
I'm new to sockets, but I'm sure this is not how it should work. The code running in browser is really simple, it should just connect to socket and log all received data to console:
index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.socket.io/socket.io-1.2.0.js" charset="UTF-8"></script>
</head>
<body>
<script type="application/javascript">
var Sockets = io.connect('http://localhost:4000');
Sockets.on('Test', function (data) {
console.log(data);
});
</script>
</body>
</html>
Also, my server file looks like this:
server.js
var app = require('express')();
var http = require('http').Server(app);
var bodyParser = require("body-parser");
var io = require('socket.io')(http);
var port = 4000;
http.listen(port, function () {
console.log('Server running at port ' + port);
});
var urlencodedParser = bodyParser.urlencoded({extended: false});
app.post('/', urlencodedParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
var post = req.body;
io.emit("Test", post.data);
console.log(post.data);
res.send('true');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
When I run the server node server.js, I got the Server running at port 4000 message and everything seems fine. But when I open the index.html in my browser, the node console is spammed by a user connected messages. Instead of connecting one client, the browser makes dozens of requests every second. When I close the browser, there is no output for some time, and then the node console is spammed by user disconnected messages.
This server should redirect all data sent via POST to connected sockets. When I make this POST request, the node server receives it (I know because it print's it into node console). But it's not received by the socket client, as there is no output in browser console (but the browser still makes dozens of new connections every second.
What is wrong here? First I thought I just messed up, so I went back and copy-pasted code from tutorial I found (not in English, but in Czech), but nothing changed. The tutorial has a lot of positive feedback, so there is propably something wrong with my computer. But what?
I had experienced the same issue, by following an example where the client was using the source of socket.io from this cdn: https://cdn.socket.io/socket.io-1.2.0.js
Tons of clients created whenever I tried to run the file (no matter if i just double clicked the html file, or if I put it under a web server, like IIS) . I then realized it might be an older version, and I just took the latest one released from this source: https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js
Everything works fine now.
Hope this helps
So to find what exactly was wrong, I downloaded example socket chat from socket.io website. When I runned it, I experienced exactly the same wrong behaviour - browser is opening many socket connections every second instead of keeping one.
So I deleted node_modules folder and used npm to install these modules again and whoa, it worked. So propably the files just corrupted during download or whatever it was, but doing the same procedure again was working this time.
Your configuration of running that page from a different web server than your socket.io server is on won't work as you have it. It will take one of three changes to make it work:
You can use the "same origin" for the web page and the socket.io connection by loading the web page from the same server that your socket.io. That means you need to load the web page directly from your socket.io web server.
You can configure your socket.io web server to accept cross origin connections (CORS connections).
You can configure your socket.io client to connect directly using webSocket without doing socket.io's usual preview with a regular http request.
If you're testing something you intend to deploy for real, you may as well just make your existing socket.io web server server your web page and load the web page directly from that.
Another possible cause of a situation like this is an incompatible client and server version of socket.io. You should make absolutely sure that you have the same version of socket.io on client and server. If you get the client socket.io library from /socket.io/socket.io.js from your socket.io web server, the the client version will automatically always match the server version. The way you are loading it from a CDN, you have to manually make sure you have identical versions.
Having this simple express app example:
var express = require('express')
var app = express()
app.use(express.static(__dirname+'/public'))
app.get('/', function(request,response) {
response.send("This wont matter if we got an index.hml after all")
})
app.listen(2311, function() {
console.log("app escuchando en Maricela DDMM")
})
And at /public I got an index.html.
When I get rid of such html the string in the send() method will be sent, received and rendered at browser.
What does actually happen with the response.send() string talking about the HTTP response, as the HTML is which is send and so rendered at browser?
Express goes through the chain of middleware in the order in which it was added. You have added express.static as the first middleware, so it will be ran first.
In the event express.static cannot find a file, it calls next(), allowing the next bit of middleware to run. This is your handler set up with app.get('/' //..., which sends the data as you have told it to.
I think it basically sets up the header information based on the parameter in send and then send the http response