同时向同一路由发出两个不同的POST请求

Two different POST requests being made to the same route at the same time

本文关键字:两个 请求 POST 路由      更新时间:2023-09-26

我正在创建一个投票应用程序,我有一个问题,我不知道如何解决。我觉得我的应用结构很糟糕。我有一个POST路由,像这样

app.route('/poll-create')
        .post(function(req, res) {
            var userID; //variable to store the authentication id for the user
            var incoming_id = Object.keys(req.body)[0];
            console.log(incoming_id);
            serverHandler.newPoll(req, res, db, function(id) {
                user_id = id;
            });
            res.redirect('/new-poll');

        });

我将一些形式的数据传递给这个路由,像这样从HTML

<form action='' method='post' enctype='multipart/form-data' name='new-poll-form'>
                    <div class='form-group'>
                        <label>Title</label>
                        <input type='text' name='title' class='form-control' placeholder='Title' />
                    </div>
                    <div class='form-group'>
                        <label>Options</label>
                        <textarea class="form-control poll-options" rows="5" placeholder='Options' name='options'></textarea>
                    </div>
                    <button type='submit' class='btn btn-primary submit-butt'>Submit</button>
                   </form>

表单中输入的数据直接发送到路由,而不需要我的AJAX请求。我认为这是因为我在表单中设置了方法='post'。

现在,我的问题是,我还需要从链接到上述HTML文件的JavaScript文件中传入一个对象。我是通过AJAX调用来实现的,比如

$('.submit-butt').on('click', function() {
                        console.log('From in here');
                        ajaxFunctions.ready(ajaxFunctions.ajaxRequest('POST', appUrl + '/poll-create', response.authResponse.userID, function(data) {
                        }));
                    });

下面是AJAX函数

'use strict';
var appUrl = window.location.origin;
var ajaxFunctions = {
  ready: function ready (fn) {
      if (typeof fn !== 'function') {
         return;
      }
      if (document.readyState === 'complete') {
         return fn();
      }
      document.addEventListener('DOMContentLoaded', fn, false);
  },
  ajaxRequest: function ajaxRequest (method, url, data, callback) {
      var xmlhttp = new XMLHttpRequest();
      console.log('Inside ajaxRequest');
      console.log(data);
      xmlhttp.onreadystatechange = function () {
         if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            callback(xmlhttp.response);
         }
      };
      xmlhttp.open(method, url, true);
      xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
      xmlhttp.send(data);
  }
};

因此,我面临的第一个问题是,当我尝试console.log通过AJAX请求发送的数据时(假设我发送一个对象),我得到的输出是{'object object ': ' '}。这就是为什么我选择只发送来自该对象的userID。在这种情况下,我得到这个,{'userID': ' '}。这很烦人,但我至少可以解决它。

我的第二个问题是,即使我解决了第一个问题,我实际上是对同一路由进行了两个AJAX调用。因此,我不能同时访问表单数据和userID。因此,我不能将它们插入到单个文档中。我该如何解决这个问题?有没有比我现在做的更好的传递数据的方法?请帮助!我使用body-parser来解析传入的数据,使用formidable来解析传入的表单数据。

你应该只发出这样一个请求:

$('.submit-butt').on('click', function() {
    var formData = {}; // Prepare form data.
    // Add code to get form data as json and insert it in formData
    // You can either use Javascript for this or, with jQuery you can look into https://api.jquery.com/serializeArray/.
    formData.userId = response.authResponse.userID; // This is how you add new data.
    // Make ajax request with formData.
    return false; // It is important to return false so the normal form POST request will not trigger, since you already did all that job with Ajax.
});

最简单的方法可能是一次性发送所有内容(除了您显然不知道的ID)。您可以使用表单或AJAX来做到这一点。您可以使用jquery之类的东西来收集表单数据,或者甚至只是一个简单的函数,在将数据作为JSON发送之前从表单中提取数据。