Node.js服务器和客户端之间的变量

时间:2022-02-10 16:07:59

I run a simple http server with Node.js:

我用Node.js运行一个简单的http服务器:

var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');
var sensor = require('ds18x20');
var temp = sensor.get('sensorID');

http.createServer(function(req,res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end(index);
}).listen(80);

console.log(temp);

my index.html file:

我的index.html文件:

<html>
   <head>
   </head>
<body>
My temperature:
//space for variable: temp
</body>
</html>

Now, I want to print the server-side variable: temp in my index.html file. But I have no idea how to do it.

现在,我想在index.html文件中打印服务器端变量:temp。但我不知道该怎么做。

Maybe somebody can help me with the exchange of Variables from the server to the client.

也许有人可以帮助我从服务器到客户端交换变量。

2 个解决方案

#1


26  

As you can read in @WebServer's answer there is a variety of template engines in node.
I want to give you an example of using one of them - EJS:

正如您在@WebServer的答案中所读到的那样,节点中有各种模板引擎。我想举一个使用其中一个的例子 - EJS:

First install it:

首先安装它:

npm install ejs

server.js:

server.js:

var http = require('http');
var ejs = require('ejs');
var fs = require('fs');

http.createServer(function(req,res) {
  res.writeHead(200, {'Content-Type': 'text/html'});

  //since we are in a request handler function
  //we're using readFile instead of readFileSync
  fs.readFile('index.html', 'utf-8', function(err, content) {
    if (err) {
      res.end('error occurred');
      return;
    }
    var temp = 'some temp';  //here you assign temp variable with needed value

    var renderedHtml = ejs.render(content, {temp: temp});  //get redered HTML code
    res.end(renderedHtml);
  });
}).listen(80);

Your view might look like this:

您的视图可能如下所示:

<html>
   <head>
   </head>
<body>
My temperature: <%= temp %>
</body>
</html>

EJS also escapes temp (and other variables you pass to the view) for you, so you don't have to worry about XSS attacks.

EJS还会为您逃避临时(以及传递给视图的其他变量),因此您不必担心XSS攻击。

Edit

编辑

You can also compile the template if you don't want to read the file on each request:

如果您不想在每个请求上读取文件,也可以编译模板:

var http = require('http');
var ejs = require('ejs');
var fs = require('fs');

//we are not in a request handler so we may use readFileSync
var content = fs.readFileSync('index.html', 'utf-8');
var compiled = ejs.compile(content);

http.createServer(function(req,res) {
    var temp = 'some temp';

    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(compiled({temp: temp}));
}).listen(80);

Edit 2 (answering your comment question)

编辑2(回答你的评论问题)

Here is a simple example of using Express and AJAX:

以下是使用Express和AJAX的简单示例:

server.js:

server.js:

var http = require('http');
var express = require('express');
var app = express();

app.configure(function() {
    app.set('view engine', 'ejs');  //tell Express we're using EJS
    app.set('views', __dirname + '/views');  //set path to *.ejs files
    app.use(app.router);
    //put your static files (js, css, images) into /public directory
    app.use('/public', express.static(__dirname + '/public'));
});

//get some server data for sending it to the client
var getData = function() {
    return Math.random().toString();
}

app.get('/', function(req, res) {
    //render index.ejs file
    res.render('index', {val: getData()});
});

app.get('/ajax', function(req, res) {
    res.send(getData());
});

http.createServer(app).listen(80);

views/index.ejs:

意见/ index.ejs:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="/public/js/request.js"></script>
</head>
<body>

    <h1>Val: <span id="val"><%=val%></span></h1>

    <button id="loadRequest">Refresh</button>

</body>
</html>

public/js/request.js:

公共/ JS / request.js:

$(function() {
    $('#loadRequest').click(function() {
        $.get('/ajax', function(res) {
            $('#val').text(res);
        });
    });
});

Hope this helps

希望这可以帮助

#2


-1  

You need a templating engine to write some data into page. check out https://github.com/joyent/node/wiki/modules#wiki-templating

您需要一个模板引擎将一些数据写入页面。看看https://github.com/joyent/node/wiki/modules#wiki-templating

#1


26  

As you can read in @WebServer's answer there is a variety of template engines in node.
I want to give you an example of using one of them - EJS:

正如您在@WebServer的答案中所读到的那样,节点中有各种模板引擎。我想举一个使用其中一个的例子 - EJS:

First install it:

首先安装它:

npm install ejs

server.js:

server.js:

var http = require('http');
var ejs = require('ejs');
var fs = require('fs');

http.createServer(function(req,res) {
  res.writeHead(200, {'Content-Type': 'text/html'});

  //since we are in a request handler function
  //we're using readFile instead of readFileSync
  fs.readFile('index.html', 'utf-8', function(err, content) {
    if (err) {
      res.end('error occurred');
      return;
    }
    var temp = 'some temp';  //here you assign temp variable with needed value

    var renderedHtml = ejs.render(content, {temp: temp});  //get redered HTML code
    res.end(renderedHtml);
  });
}).listen(80);

Your view might look like this:

您的视图可能如下所示:

<html>
   <head>
   </head>
<body>
My temperature: <%= temp %>
</body>
</html>

EJS also escapes temp (and other variables you pass to the view) for you, so you don't have to worry about XSS attacks.

EJS还会为您逃避临时(以及传递给视图的其他变量),因此您不必担心XSS攻击。

Edit

编辑

You can also compile the template if you don't want to read the file on each request:

如果您不想在每个请求上读取文件,也可以编译模板:

var http = require('http');
var ejs = require('ejs');
var fs = require('fs');

//we are not in a request handler so we may use readFileSync
var content = fs.readFileSync('index.html', 'utf-8');
var compiled = ejs.compile(content);

http.createServer(function(req,res) {
    var temp = 'some temp';

    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(compiled({temp: temp}));
}).listen(80);

Edit 2 (answering your comment question)

编辑2(回答你的评论问题)

Here is a simple example of using Express and AJAX:

以下是使用Express和AJAX的简单示例:

server.js:

server.js:

var http = require('http');
var express = require('express');
var app = express();

app.configure(function() {
    app.set('view engine', 'ejs');  //tell Express we're using EJS
    app.set('views', __dirname + '/views');  //set path to *.ejs files
    app.use(app.router);
    //put your static files (js, css, images) into /public directory
    app.use('/public', express.static(__dirname + '/public'));
});

//get some server data for sending it to the client
var getData = function() {
    return Math.random().toString();
}

app.get('/', function(req, res) {
    //render index.ejs file
    res.render('index', {val: getData()});
});

app.get('/ajax', function(req, res) {
    res.send(getData());
});

http.createServer(app).listen(80);

views/index.ejs:

意见/ index.ejs:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="/public/js/request.js"></script>
</head>
<body>

    <h1>Val: <span id="val"><%=val%></span></h1>

    <button id="loadRequest">Refresh</button>

</body>
</html>

public/js/request.js:

公共/ JS / request.js:

$(function() {
    $('#loadRequest').click(function() {
        $.get('/ajax', function(res) {
            $('#val').text(res);
        });
    });
});

Hope this helps

希望这可以帮助

#2


-1  

You need a templating engine to write some data into page. check out https://github.com/joyent/node/wiki/modules#wiki-templating

您需要一个模板引擎将一些数据写入页面。看看https://github.com/joyent/node/wiki/modules#wiki-templating