Pass req res objects into socket.io? - javascript

I am a little confused how I can interact with the socket when I need to pass in data from my routes file. I have the standard setup using node.js, express, mongodb etc.
I'll run my socket.io logic inside server.js, and I include the routes.js inside that file.
var routes = require('./app/routes');
In this case I need to run some io.sockets inside my routes.js file.
My question is what is a good way to do this? I could run that specific route inside server.js but that gets messy. If I were to use sockets in my routes.js do I need to re-require
var io = require('socket.io').listen(server);
That means I need to create a new http server object, and I don't like that since I am requiring this file in server.js, this seems like a counter-intuitive move to me.
So how do I make a request to the server and pass for example a user name?
Example:
app.get('/profile', isLoggedIn, function(req, res) {
res.render('profile', { user : req.user });
io.sockets.on('connection', function (socket) {
console.log(socket);
console.log(req.user); // Here I have access to the user and can pass that around in my sockets
});
});
I am also using route middleware, so I'd like to keep that in my routes.js, IDK I am just confused what I should do, hopefully someone understands my angle here?
Edit:
What about passing something into the routes?
routes.initialize(app, passport);

You can get the req and res objects directly in the socket by invoking socket.request (a Getter function which is available via __proto__). See docs.
I was then able to find req.user in socket.request.client.user.

Related

node js express js request response circle

I am curious and really willing to learn and understand the whole concept behind the request and response circle of all backend
my question is I have a node js express framework
app is started
app.use('/api',router)
require('./routers/user')(router)
require('./routers/uretim')(router)
require('./routers/durus')(router)
require('./routers/rapor')(router)```
all my functions are called and executed and waiting for a request
since the order of this app is first use
app.use('/api',router)
then the router is called at this particular point router function has nothing attached to it,
so does it mean as we started our application we have created the routes with the executed functions below the app.use
main question
user enter ..../api
our back end was hit
what is the first process, or function that happens within our backend?
So the USE is used to load middleware, what you have is to use the router middleware on the /get url..
A better example of what is happening here is to define some action middleware on that url :
app.use("/api", (req, res, next) => {
// For example, a GET request to `/api` will print "GET /api"
console.log(`${req.method} ${req.url}`);
next();
});
When you start your server, if you hit your /api url, it will log the request info in the console and continue.
However the other URL's will not.. So you can tailor specific middleware for certain endpoints.
As for your routing itself, you will need to define the routes and their controller logic. Something like :
// HTTP GET Request Definition
app.get('/api',(req, res) => {
res.send("Hey, you hit API");
} );
This will happen after the middleware has been actioned.
Express

Running a NodeJS cron from cron-job.org

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:

Require statements needed when something is already attached to a request in Node/Express?

Let's say I have an app in Node with the main elements of the application in a file at the root directory called app.js. Now let's say I have a route in ./routes/index.js.
If some of my middleware in app.js attaches handlers to the request, do I need to require the library that added that handler when handling the route in index.js?
I.e. in app.js:
var flash = require('connect-flash');
...
app.use(flash());
And in index.js:
var flash = require('connect-flash'); // ???
router.get('/', function(req, res, next) {
res.render('index', { message: req.flash('loginMessage') });
});
It appears to work without the require statement in index.js, but I want to make sure I'm understanding this conceptually. Once something is attached to the request, it stays with the request wherever it goes, right?
When you create an express application you create a "tree" so to speak, meaning that wherever you apply middleware any descending route will go through that function. So if we put the middleware at the top of our application all requests will go through that function. You only need to require the middleware wherever you are applying it to the application.
No, you don't. You only need require to get access to exported items from the module. If you don't need to access them (for instance, because something is already accessible as a property on req), you don't need the require.

Show Attached Middleware Functions in Console

I have to admit I'm rather surprised I didn't find any info on this through Google. Perhaps I wasn't looking hard enough.
Basically, I want to find information on the various middleware functions my Express.js app is using, preferably via a bash-like console. Logging the express() function itself does not log the sub-functions, such as trace() or mkcol(). These are shown as attributes of the express function object, as, for example, trace: [Function], or emit: [Function: emit]; their bodies and current contents are not shown. I am able to log the function bodies through e.g. express().once.toString(), as said in several answers, including this one.
This only shows the function body as it was before I called it (when I added all the middleware), not what said body is now. It does not show the middleware I had Express use().
How do I show these middleware functions in the console as they are now? For example, if I define:
express = require('express');
server = express();
flash = require('connect-flash');
bodyParser = require('body-parser');
server.use(flash());
server.use(bodyParser.json());
server.use(bodyParser.urlencoded());
how do I see that Express now uses the flash middleware, and, separately, how do I see that Express now uses the middleware that consists of whatever function is exported by the connect-flash module? If one or both of these would not work for "whatever the bodyParser.json()/bodyParser.urlencoded() function is", is there another way to log that? As I said, it is not enough to simply console.log Express's use() function, or, if it is, I was not able to find the trick. There are a million ways in which a middleware function can be defined & use()d, so I don't expect any answer to work for all of them, but "as many as possible" would be nice.
Any answer should work for nested middleware, as well, as, for example, the Router and vhost middlewares can and usually do use() other middleware, and are in fact Express apps themselves.
Closest thing I know of is to run your app with the DEBUG environment variable set to express:router like this: DEBUG=express:router node server.js and watch the output as you use the app. Many of the functions you use as middleware are going to be anonymous since it is common to define them like this: app.get('/foo', function(req, res) {...}); thus express doesn't even have access to something as basic as a human-readable name for that route handler function.

How are HTTP responses managed by Node JS express?

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

Categories