简体   繁体   中英

Sharing variables between client and server in node

Let me preface by saying that I have spent a considerable amount of time trying to figure out the solution to this problem but I have not discovered something that works. I am using node and want to share a variable between my app.js server file and a client side javascript file (demo.js).

I run node app.js to launch the server and demo.js runs in the client. I have tried using module.exports and export but when I try importing in the demo.js file or referring to the module.exports var I get errors. Maybe I'm approaching this is in the wrong way.

For example, I am trying to use the node wikipedia package to scrape data. I have the following in my app.js file:

var wikipedia = require('node-wikipedia');

wikipedia.page.data('Clifford_Brown', { content: true }, function(response) {
    console.log(response);
    export const response = response;
    module.exports.data = response
});

In my demo.js file I have tried importing this response var and using the module.exports var but I have been unsuccessful.

Anyone have any solutions to this issue or different approaches I should take?

Browser javascript files run in the browser. node.js javascript files run on the server. You cannot directly export things from one to the other. They are on completely different computers in different locations.

It is very important for developers to understand the notion that server-side code runs on the server and client-side code runs on the browser. The two cannot directly call each other or reach the other's variables. Imagine your server is in a data center in Seattle and the browser is running on a computer in Venice.

See How to access session variables in the browser for your various choices described for a previous answer.

In a nutshell, you can have the server insert a javascript variable into the generated web page so that when the javascript runs in the web page on the browser, it can then access that variable in its own page. Or, you can create an Ajax call so the client can request data directly from the server. Or you can have the server put some data in a cookie which the Javascript in the browser can then access.

If the data is easily known by the server at the time the page is generated and you are using some sort of page template system, then it is very easy to just add a <script> tag to the generated page that defines one or more Javascript variables that contain the desired information. Then, the client-side Javascript can just refer to those variables to have access to the data.

To pass data in http there is a request message and response message and the data needs to be inside that message.

In the request you can either pass variables in the request URL

http://host_name/path?key=value

Or inside the request body or headers.

In the response you pass back variables in the response header or response body

First Example:

One way of processing a URL request from the browser explicitly while passing variables is to set up your server to render a html page with those variables embedded.

If you use a templating engine like jade, you can consume the sent variables directly into the template using res.render({ key: 'value' }) rather than using a promise based api call which would run when the user performs some action on the client.

For instance.

// SERVER setup rendering engine
app.get('/', function(req, res) {
    res.render( 'index', { key: 'value' })
}

Which will render index.html to the client with the key-value pair passed to the template file used to serve up the index.html (for example jade or ejs).

Second Example:

Using axios you can set up an action to call a server api (you can also pass variables in the URL, headers or body). Using the promise pattern you can then use these variables after the server api has responded.

// CLIENT setup axios
axios.get(URL + '/getkeyvalue')
    .then(function(response) {
        const value = response.data.key
    })

On you server using express you (this is where you would get the optional request variables mentioned above) send back response variables in the body like this.

// SERVER setup express
app.get('/getkeyvalue', function(req, res) {
    res.send({ key: 'value' })
}

Note that these are simple examples.

They are too completely different systems. The best way to accomplish what you're trying to do is the create a variable in your html on the server side by stringifying your data

<script> var my_data = <%= JSON.stringify(data) %> </script>

Thats an example using ejs, a common templating language in expressjs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM