简体   繁体   中英

How to pass value from app.js file to my client side file in node js?

Here I have one doubt, how can i pass value from node js app.js file to my client side js file.

Here My app.js file

var express  = require('express');
var app      = express();                               
var port     = process.env.PORT || 3000;
var bodyParser = require('body-parser');
var facebookAppId = '123456789023'


app.configure(function() {
app.use(express.static(__dirname + '/dist'));   
app.use(express.logger('dev')); 
app.use( bodyParser.json() );  
app.use( bodyParser.urlencoded() );     
app.use(express.methodOverride());  
    });
app.listen(port);

Inside my dist folder i have index.html . that used to start run initially when i start app.js . So i would like to use the facebookAppId in my client side.How can i do that ?

Put it in it's own json file under a shared folder, then you can just require it like so in node:

shared/facebookInfo.json

{
    "facebookAppId" : 123456789023
}

app.js

var facebookAppId = require('./shared/facebookInfo').facebookAppId;

...
// make sure to mount the directory as well so you can access it from the front end:
// it's being mapped to /shared here
app.use('/shared', express.static(__dirname + '/shared')); 
...

And on the client side include it with ajax trough jquery or $http, whatever you are using.

A different approach could be to not put the file under a shared mounted folder, but include it during your front end build process.
This way you don't have to do an additional request to get in to your frontend and it's included more implicitly.

This is probably the most popular plugin to do that:
https://github.com/gruntjs/grunt-contrib-concat

This is off course somewhat assuming your frontend and backend are in the same repo. If they are in a different repo, you will have to put your shared data in a seperate repo as well, but that's a whole different question.

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