Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在MVC Javascript中在控制器之间传递数据_Javascript_Node.js_Express - Fatal编程技术网

在MVC Javascript中在控制器之间传递数据

在MVC Javascript中在控制器之间传递数据,javascript,node.js,express,Javascript,Node.js,Express,我正在使用Express和Node构建一个应用程序 我有一个名为“/newpoll”和“/poll create”的路由 //The poll-create route will give the user the option of creating a poll app.route('/poll-create') .get(function(req, res) { res.sendFile(path + '/public/pollcreatio

我正在使用Express和Node构建一个应用程序

我有一个名为“/newpoll”和“/poll create”的路由

//The poll-create route will give the user the option of creating a poll
    app.route('/poll-create')
        .get(function(req, res) {
            res.sendFile(path + '/public/pollcreation.html');
        });



    //This is the route for creating a new poll by authenticated users. Authentication still needs to be added.     
    app.route('/poll-create')
        .post(function(req, res) {
            console.log('inside poll-create post request');
            console.log(req.body);

            serverHandler.newPoll(req, res, db, function(id) {
                console.log('It worked');
                req.session.poll_id = id;
                res.json(id);
            });

        });

    //The above response will redirect to this route, and here is where the poll data will be served up
    app.route('/new-poll')
        .get(function(req, res) {
            console.log('Inside get request for new poll');
            console.log(req.session.poll_id);
            res.sendFile(path + '/public/pollvisualization.html');
        });

    //This is the route for making a post request to the same URL. Specifically to obtain the document inserted previously through creating a new poll
    app.route('/new-poll')
        .post(function(req, res) {
            console.log('Inside new poll post');

            serverHandler.check(db, req.session.poll_id, function(err, doc) {
                if (err) {
                    console.log('There is an error');
                    throw err;
                }
                if (doc) {
                    res.json(doc); //send the json document generated by the poll creation by mongoDb to pollvisualizationClient.js through ajax-functions.js
                }
            });

        });
现在,我有两个控制器,controllerData和ControllerOnData

controllerData使用AJAX调用将数据传递到上述POST请求。ControllerOnData需要访问controllerData传递给POST请求的数据

我怎样才能以最简单的方式做到这一点?本质上,我的问题归结为在Express和Node中在视图控制器之间传递数据的最简单方法是什么

我现在的做法是,使用controllerData的数据发出POST请求,然后在没有ControllerOnData数据的情况下发出POST请求,然后尝试区分POST请求中的两个调用。但是,这似乎是一个巨大的痛苦

注意:我的应用程序中没有使用AngularJS。提到这一点是因为我在StackOverflow上看到的所有答案都提到了用AngularJS实现这一点的方法

编辑: 控制器数据代码

(function() {
    $(document).ready(function() {
        if (typeof FB !== 'undefined' && FB !== null) { //this if statement is to ensure FB object loads before doing anything else 

            FB.Event.subscribe('auth.authResponseChange', function() {
                FB.getLoginStatus(function(response) {

                    var data = {}; //setting up the data object to fill with objects

                    $('.submit-butt').on('click', function() {

                        data.formData = $('form').serializeArray(); //this is the form data from the form
                        data.facebookData = response.authResponse; //facebook object data
                        console.log(data);

                        data = JSON.stringify(data); //this is done to pass the data and parse it through body parser. Not sure why it works this way. 
                        ajaxFunctions.ready(ajaxFunctions.ajaxRequest('POST', appUrl + '/poll-create', data, function() {
                            window.open('https://fcc-votingapp-redixhumayun.c9users.io/new-poll', '_self');
                        }));

                        return false; //setting this statement to false ensures that the form data does not automatically submit independent of the AJAX call 
                    });
                });
            });

        }
        else {
            location.reload(); //reloads the page in case the if statement is not satisfied. 
        }

    });
})();
ControllerOnData的代码

(function() {
    var value; //variable to store the value of the radio option selected
    var custom_flag = false; //flag variable to check whether Custom radio button was selected

    //This is where the AJAX request is initialized
    ajaxFunctions.ready(ajaxFunctions.ajaxRequest('POST', appUrl + '/new-poll', null, function(data) {

        //Parsing the data into JSON format below
        $(document).ready(function() {
            //this is the form data that has been provided via the AJAX request
            data = JSON.parse(data);
            console.log(data);

            var options_count = data[0].options_counter; //this variable stores the options_counter, that is the number of options

            var options_array = getSeperatedOptions(data[0].options);

            var options_length = Object.keys(options_count).length; //finding out the length of the options_counter object in this line

            //updating the header element
            $('h1').html(data[0].title);

            //Invoking the function that will create all of the options required by the user
            createOptions(options_length, options_array);

            //This method here checks to see if the user has selected Custom as their option
            $('.radio-options').on('click', function() {
                var entered_value = getEnteredOption(options_length); //calling this function to check if Custom has been chosen.
                if (entered_value == options_length) { //parseInt of entered_value will return a NaN. Use this to check against the number that is returned for parseInt of the other radio buttons
                    $('.custom-div').show();
                    custom_flag = true; //set the custom flag to true here because Custom radio button was selected
                }
            });

            $('.btn-danger').on('click', function() {
                ajaxFunctions.ready(ajaxFunctions.ajaxRequest('POST', appUrl + '/new-poll/delete-poll', data[0]._id, function(data) {
                    console.log('This is data: '+data); //data contains the number of documents deleted
                }));
            });

            //Submit button event click handler
            $('.submit-butt').on('click', function() {
                //if statement decides whether the radio button selected was the Custom radio button
                if (custom_flag == true) {
                    var entered_value = $('.custom-text').val();
                    value = entered_value; //assigning the local entered_value to a global value variable to use in the next AJAX function
                }

                //else if statement decides whether a radio option button is checked or not! Fires only if Custom not selected
                else if ($('.radio-options').is(':checked')) {
                    var entered_value = getEnteredOption(options_length); //Function call to get option entered by user. Returns the value of the radio button
                    value = entered_value; //assigning the local entered_value to a global value variable to use in the next AJAX function
                }

                //Fire this else statement if no option is selected but Submit button is clicked
                else {
                    window.alert('You need to choose an option before trying to submit');
                }

                if (value.length > 0) {
                    var dataToPass = {}; //defining this object to pass data as JSON
                    dataToPass.value = value;
                    dataToPass = JSON.stringify(dataToPass); //stringify data to pass it through without error

                    ajaxFunctions.ready(ajaxFunctions.ajaxRequest('POST', appUrl + '/new-poll/option-entered', dataToPass, function(data) {

                        //This object contains the returned value from the above AJAX call 
                        data = JSON.parse(data);

                        var optionsArray = getSeperatedOptions(data.value.options); //Keep the difference between optionsArray and options_array in mind AT ALL TIMES!

                        //This function is used to convert the options_counter object to an array so that it can be used to render the chart using ChartJS
                        var options_counterArray = convertOptionsCounterToArray(data.value.options_counter);

                        //call to function to create chart here
                        createChart(optionsArray, options_counterArray);
                    }));
                }
                else {
                    window.alert('Hi!');
                }


            });
        });
    }));

})();

编辑:我还更新了使用会话的路由

所以我假设您的控制器在客户端
http
是一种无状态协议。因此,为了在状态之间传递数据,需要实现某种缓存机制。有几种方法可以做到这一点:

  • 根据要保存数据的时间长度,直接使用HTML5
    localStorage
    sessionStorage
    API。确保在处理完数据后清除存储,以防止命中。使用
    localStorage
    将允许您使用数据,直到手动清除为止<只要选项卡打开,代码>会话存储将一直有效
  • 使用其他类型的客户端存储,如Web SQL
  • 如果希望在页面重新加载周期内存储数据(即,重新加载页面后将丢失数据),可以创建一个Javscript单例函数,并将其作为依赖项注入两个AJAX调用中,然后将响应存储在该对象中。这与AngularJS的服务提供商的情况类似。这比其他两种方法更干净,但当然寿命更短(除非与上述存储API之一结合使用)

你能说明你的控制器是如何定义的吗?你是指目录结构还是定义它们的代码?定义它们的代码好的,只是更新了edits@ZaidHumayun你在这方面有什么进展吗?
var UserStore = (function(){
  var _data = [];

  function add(item){
    _data.push(item);
  }

  function get(id){
    return _data.find((d) => {
        return d.id === id;
    });
  }

  return {
    add: add,
    get: get
  };
}());