如何将数据从nodejs推送到浏览器

How to push data from nodejs to browser?

本文关键字:浏览器 nodejs 数据      更新时间:2023-09-26

我正试图了解如何将数据从我的nodejs服务器.js推送到我的浏览器。根据我的网页搜索,我找到了这个脚本:

Server.js

var express = require('express');
var app = express();
var userCount = 0;
var userbytwo = 0; /* added var definition for userbytwo here */
app.get('/', function(req, res){
  userCount = userCount + 1;
  /* add statement to increment userbytwo by two here */
  userbytwo = userbytwo + 2;
  console.log('userCount: '+userCount+' userbytwo: '+userbytwo);
  res.render('index', {userCount: userCount, userbytwo: userbytwo});
 /* updated this line */
});

index . html

The user count in my nodejs application is: <%= userCount %>
The user by two count in my nodejs application is: <%= userbytwo %>
如果我已经启动了server.js,我希望<%= userCount %><%= userbytwo %>将被填充。但事实并非如此。

1)我的剧本有什么问题?

2)如何将数据推送到浏览器(index.html)?

谢谢你的帮助。

您需要首先将视图引擎设置为ejs,如文章所建议的:

app.set('view engine', 'ejs');

然后,重命名你的视图文件index.ejs而不是index.html,你应该很好去。

app.post('/', function (req, res) { res.send('POST request to the homepage'); });

查看本教程中的更多信息:

http://expressjs.com/en/guide/routing.html