首页 > 解决方案 > 从 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();
};

标签: node.jsreactjsexpress

解决方案


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


推荐阅读