javascript - 从 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。
重申一下,我的问题是:
- 如何从客户端 JavaScript 文件(不是 HTML)中获取变量?
- 将这些变量发送回客户端的最佳方法是什么?
任何帮助将不胜感激。
解决方案
推荐阅读
- python - python禁用自动重定向?
- r - R闪亮的书签桶列表
- php - 是否可以使用 laravel 默认身份验证在不使用护照的情况下让用户进入 api
- reactjs - 没有 useEffect 钩子不能做什么?
- php - 有没有办法将 2 个 foreach 和一个 for 循环一起循环?
- reactjs - 在 reactjs 中使用 firebase 的 Google 身份验证不起作用
- fonts - 如何合并表情符号 TTF 文件和字体 TTF 文件?
- docker-compose - Docker compose rabbitmq 在启动时创建队列
- c# - 反序列化具有不同表示的对象
- c# - 查看 HttpClient.PostAsync 的响应正文