Hi. 让我们首先说我有一个 Express 服务器,可以将 html 网站发送到浏览器。
在该服务器上,我还有一个db.js
文件,其中包含一个 Object 变量:
const settings = {
// Some example settings here:
ok: true,
cost: 50,
value = "Hello, World!"
};
module.exports = settings;
我只能通过以下方式访问它:
// First, requiring the file:
const file = require("./db.js");
// Then accessing it.
console.log(file.settings.ok)
只要它在服务器文件中,这就可以正常工作。
如何在 html 页面 (
<script></script>
( 上且没有 require(( 函数或无法识别db.js
文件中的module.exports
函数的纯 javascript 文件中访问此值?
尝试使其工作:
使用它只是正常的,就像一个节点.js文件(它不是(>require(( 方法是未解决的,预期的。
使用 RequireJS 库>失败,因为网站无法识别
module.exports
是什么。(从 db.js 文件导出对象时需要(。
可能的修复,我不一定知道如何做:
通过快速文件将此变量发送到 HTML 文件
以某种方式将所需的节点.js语法添加到html javascript文件中
如果您缺少有关我的情况的任何信息,我非常欢迎为您提供,只需发表评论。
编辑:我确实需要更改值,所以
read only
不会削减它。
您可以将数据提交到服务器以修改ok
值。
服务器可以运行node server.js
,它将在 http://localhost:3001 上运行。
在此示例中,提交表单将重定向到服务器呈现的 html,并显示修改后的值。
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const settings = require('./db');
const PORT = 3001;
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/modify', (req, res) => {
const { body } = req;
settings.ok = body.ok;
res.set('Content-Type', 'text/html');
res.send(`<h2>Value ok is now set to: ${settings.ok}</h2>`);
});
app.get('/', function(req, res) {
res.sendFile('./index.html', { root: __dirname });
});
app.listen(PORT, () => {
console.log(`Server is running at ${PORT}`);
});
您的客户可以将一个简单的表单发布到该服务器。这是索引.html。
<!DOCTYPE html>
<html>
<body>
<h1>Super app</h1>
<form id="my-form" action="http://localhost:3001/modify" method="POST">
<input type="text" name="ok"></input>
<button type="submit">Submit form</button>
</form>
</body>
</html>
正如其他人所评论的那样,如果不编写和调用一些服务器端代码,就无法修改服务器上的值,但是如果您需要做的就是将文件传递给浏览器并在浏览器上下文中读取和修改其值,那么这是可能的。 @Bergi那里有几个选项,我还有一个:
如果您希望在客户端和服务器之间共享代码模块,我强烈建议采用较新的"ES6 模块"语法。因此,您的代码将如下所示:
// settings.js
export const settings = {
// Some example settings here:
ok: true,
cost: 50,
value = "Hello, World!"
};
然后,您要使用或修改设置的位置:
// app.js
import { settings } from "./settings.js"
settings.value = "to the Moon"
所有现代("常青"(浏览器都原生支持此功能,无需转译器,方法是在标签上使用type="module"
属性,如下所示:
<script src="app.js" type="module" />
有一个名为esm
的优秀NPM包,它在Node中也为它添加了非常好的支持(https://www.npmjs.com/package/esm(。
这将使您的代码比使用 RequireJS 等"遗留"模块加载器更具前瞻性。
您无法在浏览器中访问服务器JS文件,这将是一个巨大的安全风险。
由于您使用的是 Express,因此您只需创建一个路由,该路由返回带有设置的 JSON 对象(应用程序/json(,然后使用fetch
获取该对象的内容。
async function getSettings() {
const res = await fetch('/settings');
const json = await res.json();
// json is your settings
}