Skip to content Skip to sidebar Skip to footer

Accessing The Functions In Express On Client Side Using The Require -- Node Js

I have a to access the config variables defined in the file called test.js which has -- var aws = require('aws-sdk'); exports.connect = function(){ return aws; } Now I nee

Solution 1:

Hopefully I'm not too far off the mark with what you're trying to do here. My understanding (cobbled together between this and your previous question is that you would like something in the browser that upon click will retrieve some status information from an external API, which will then be displayed in the client.

What I would recommend doing (based on the above assumption) is defining your desired function as something to be triggered by an HTTP request to the Express server, which can perform your function and send whatever you'd like from its process back to the client.

In your server define (assuming your Express variable is app)

app.get('/request', someFunction);

In someFunction define what it is you'd like to do, how it relates to the request and response, and what to send back to the client. Express will expect the function to take request and response as arguments, but you don't necessarily need to use them:

someFunction(req,res) {
  //do whatever I'd like with aws or anything else
  res.send(foo); //where foo is whatever JSON or text or anything else I'd like the client to have to manipulate
}

On the client, you would have a function bound to onclick that would make the request to that /request endpoint. This function could use AJAX or simply render another page entirely.

This sort of organization also leaves display and behavior to the client, while the server deals with retrieving and manipulating data. This layout also resolves any concerns about require() statements on the clientside (which, while possible with things like Browserify, are not necessary and may make the code more confusing).

Solution 2:

You can't use require() on the client side, that is only a server side function provided by node.js which runs on the server. If you need config options that are shared between server and client, then you will need to make a few changes to your test.js file so it will work in both. I'm sure there are a number of ways to do this, but the way I prefer is:

Put all your configuration variables inside test.js into an object like:

this.ConfigOptions = {option1:value1, option2:value2};

The client would include the file like this:

<scriptsrc="test.js"type="text/javascript"></script>

and can access the config options via the ConfigOptions object

while the server would use require() to include the file and access the config options like this:

varConfigOptions = require('test.js').ConfigOptions;

Post a Comment for "Accessing The Functions In Express On Client Side Using The Require -- Node Js"