我正在尝试将变量从index.html传递到我的React应用,该应用已在本地Express / Node服务器上编译并运行。我尝试使用window对象,但是node.js无法识别window对象。
基本上,一旦应用程序加载完毕,index.html就会从查询字符串中获取用户信息,并将数据发送到userController。参见下面的代码
index.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>
userController.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();
};
答案 0 :(得分:0)
如果您将HTML文件作为静态文件发送,则
您可以执行以下解决方案:
通过运行命令ejs
安装npm i ejs
,然后将文件从index.html
更改为index.ejs
,
将此行添加到您的应用中
app.set('view engine', 'ejs');
并通过
res.render('index.ejs', {
// here data to pass
});
然后您可以将数据传递到index.ejs
,它将被渲染
您可以阅读docs in here,它将使图像更加清晰。
然后redux将是解决方案