BinCodinLong
BinCodinLong

Reputation: 721

pass value from node.js to javascript

I'm trying to work with Google's example code: PhotoFrame. It is built with node.js, expressjs, jQuery, etc. I need to pass a variable -- let's call it myString -- from app.js to one of the .js files -- let's call it myScript.js. I've tried at least a dozen approaches that I found at StackOverflow and elsewhere. None has worked.

Some folks have said "just use a global, even though they're 'BAD'. In app.js you:

global.myStringGlobal = myString

and in myScript you:

var myStringLocal = myStringGlobal;

Doesn't work: myStringGlobal is undefined.

Some folks say: code a little object in app.js and module.export it. Them require it in myScript. Doesn't work: require is undefined in myScript. In fact, since myScript and myOtherScripts run in the browser, require is simply un-available.

Some folks say code this in app.js:

res.render(page, {myString: myString});

Others say "No, that sends myString to the html renderer; not to myString. They're correct.

I won't drag this out by telling you the other ways I tried in vain.

This question has been asked and answered many times in various ways, but none of the answers work -- anymore? or who knows why?

So I ask again: does anyone know how to pass a variable from the node.js app.js script to some myScript.js file?

Upvotes: 1

Views: 9135

Answers (2)

Ukasha
Ukasha

Reputation: 2334

Here's the explanation.

You have to know that you have been involved into different app. Your express app is a server side app, while another would be client side app. So, the main question is, how to pass data from server to client?

If you're thinking about ajax, then you're right. I'm not using jQuery anymore, but I think you can use something like $.get(..).

server

const express = require('express');
const app = express();
const port = 8080;

// Data can be requested via GET method
app.get('/sample-api', (req, res) => {
    res.json({ text: 'Lorem Ipsum' });
});

// You can render page here...

app.listen(port, () => console.log(`Listening on port ${port}`);

client

$(function() {
    var msgFromServer;
    $.get( "/sample-api", function( data ) {
        msgFromServer = data.text;
        alert( "Received data from server!" );
    });
});

Upvotes: 1

Mark S.
Mark S.

Reputation: 4019

From Expressjs, you can pass a variable along with a page when you render it. In the render call, you name the view you're trying to render and you can pass variables along with it:

app.render('email', { name: 'Tobi' }, function(err, html){
  // ...
});

This passes a variable named 'name' to the email view with the value 'Tobi'. You can then use the variable in the HTML

<script>var name = "<%= name %>";</script>

See previous question

Upvotes: 1

Related Questions