首页 > 解决方案 > 从 Express 中的客户端 JavaScript 文件中获取变量

问题描述

我正在尝试将一个变量从我的客户端 JavaScript 文件发送到我的服务器端 app.js 文件。我知道您可以使用以下方法(使用 Express)从表单输入字段之类的内容中获取值:

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

let cityResponse;

app.post('/city', function(req,res) {
  cityResponse = {
    user_name: req.body.userName
  }
  res.sendFile(path.join(__dirname, '/client/city/index.html'));
});

但我想不直接从 HTML 中获取值,而是从 HTML 附加到的 JavaScript 文件中获取值。


除此之外,我目前正在使用 Socket.io 将数据从服务器发送到客户端,反之亦然,使用 awindow.onload让服务器知道页面何时准备就绪:

index.js

window.onload = function() {
  socket.emit('cityPageReady');
  console.log("city page ready");
};

socket.on('cityPageInfo', function(cityResponse) {
  console.log('city page info received');
  console.log(cityResponse);
  console.log(cityResponse.user_name);
  userName = cityResponse.user_name;
  document.getElementById("name").innerHTML = userName;
});

应用程序.js

var city = io.of('/city').on('connection', (socket) => {
  console.log('A user has connected!');
  socket.on('cityPageReady', function() {
    socket.emit('cityPageInfo', cityResponse);
    console.log('city page ready recieved');
  });
});

这行得通,但很多人说这是矫枉过正,或者用一个人的话来说,“用锤子杀死蜜蜂”。理想情况下,我想使用最佳方法。我知道模板引擎可以实现这一点,但我不想为了能够将单个变量发送到服务器而重写我的所有 HTML。


重申一下,我的问题是:

任何帮助将不胜感激。

标签: javascripthtmlnode.jsexpresssocket.io

解决方案


推荐阅读