node.js - 从 Index.html 到 controller.js 将变量传递给 React 编译的应用程序
问题描述
我正在尝试将变量从 index.html 传递到我的 react 应用程序,该应用程序在本地 express/node 服务器上编译和运行。我尝试使用窗口对象,但 node.js 无法识别窗口对象。
基本上一旦应用程序加载 index.html 从查询字符串中获取用户信息并将数据发送到 userController。请参阅下面的代码
索引.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta content="telephone=no" name="format-detection">
<meta content="no" name="msapplication-tap-highlight">
<meta content="user-scalable=no,initial-scale=1,maximum-scale=1,minimum-scale=1,width=device-width" name="viewport">
<title>App Frontend</title>
</head>
<body>
<div id="root"></div>
<script src="js/compiledscript.js"></script>
<script>
new AppCode({
root: document.getElementById('root'),
host: 'http://localhost:3500',
endpoints: {
folder: '/api/folder',
file: '/api/file'
},
headers: {
'Content-Type': 'application/json'
}
});
//Get iframe data query from parent
function getParamValue(paramName)
{
var url = window.location.search.substring(1); //get rid of "?" in querystring
var qArray = url.split('&'); //get key-value pairs
for (var i = 0; i < qArray.length; i++)
{
var pArr = qArray[i].split('='); //split key and value
if (pArr[0] == paramName)
return pArr[1]; //return value
}
}
var userData = {
username: getParamValue('username'),
userid: getParamValue('userid')
}
window.userData = userData;
//console.log(getParamValue('username'));
//console.log(getParamValue('userid'));
</script>
</body>
</html>
用户控制器.js
const mongoose = require('mongoose');
const path = require('path');
const fs = require('fs');
const User = mongoose.model('User');
//const users = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'data', 'users.json'), 'utf-8'));
/*
const users = window.userData;
const userid = users.userid;
exports.userid = userid;
*/
exports.getAll = async (req, res) => {
const users = await User.find();
res.json(users);
};
exports.bang = async (req, res, next) => {
await User.remove();
next();
};
exports.addNewUser = async (req, res, next) => {
await User.create(users);
// next();
};
解决方案
If you are sending the HTML file as static file,
You Can do this solution:
Solution:
install ejs
by running the command npm i ejs
then change your file from index.html
to index.ejs
,
add this line to your app
app.set('view engine', 'ejs');
and send the file by
res.render('index.ejs', {
// here data to pass
});
then you can pass data to index.ejs
and it will get rendered
you can read the docs in here it will clarify the image more.
if you can use server-side rendering
then redux would be the solution
推荐阅读
- javascript - Javascript 不替换或修改原始实例
- c# - 如何在listview中绑定listviewitem的内容?
- c++ - 读取 C++ vtable 的竞争条件。有可能吗?
- xamarin.forms - Skiasharp 旋转轮盘游戏。两物合谋
- javascript - Vue + Vuetify 服务器端渲染:CSS 在生产构建中导致`ReferenceError:文档未定义`
- python - 如何在这些类型的公式中找到“m”和“c”的值。?(公式:“Y = mxzw + c”)
- python - 在 Pytorch 中冻结单个权重
- android - 远程配置不会在 onStart() 重新获取数据
- javascript - 使用 php ajax 的 tbody 内不显示结果
- c - << 在 C 中是什么意思?