Подтвердить что ты не робот

Переменные между сервером Node.js и клиентом

Я запускаю простой http-сервер с Node.js:

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 файл:

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

Теперь я хочу напечатать серверную переменную temp в моем файле index.html. Но я не знаю, как это сделать.

Возможно, кто-то может мне помочь в обмене переменных с сервера на клиента.

4b9b3361

Ответ 1

Как вы можете прочитать ответ @WebServer, в node есть множество движков шаблонов.
Я хочу привести вам пример использования одного из них - EJS:

Сначала установите его:

npm install ejs

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);

Ваше мнение может выглядеть так:

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

EJS также пропускает temp (и другие переменные, которые вы передаете в представление) для вас, поэтому вам не нужно беспокоиться об атаках XSS.

Edit

Вы также можете скомпилировать шаблон, если вы не хотите читать файл по каждому запросу:

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);

Изменить 2 (ответить на ваш вопрос)

Вот простой пример использования Express и AJAX:

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);

просмотров /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>

общественные /JS/request.js:

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

Надеюсь, что это поможет