[英]Two different POST requests being made to the same route at the same time
我正在創建一個投票應用程序,但遇到了一個我不知道如何解決的問題。 我認為我的應用程序結構不好。 我有這樣的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請求即可直接發送到路由。 我認為這是因為我正在表單中設置method ='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調用。 因此,我無法同時訪問表單數據和用戶ID。 因此,我無法將它們插入單個文檔中。 我該如何解決? 有沒有比我目前更好的方法來傳遞數據? 請幫忙! 我正在使用body-parser解析傳入的數據,並且解析傳入的表單數據非常強大。
最簡單的方法可能是一次發送所有內容(除了您不知道的ID之外)。 您可能可以使用表單或AJAX來實現。 您可以使用jquery之類的方法來收集表單數據,甚至可以使用一個簡單的函數將數據作為JSON發送之前從表單中拉出。
您應該只發出這樣的一個請求:
$('.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.
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.