我寫的是應該從瀏覽器發送一個AJAX POST請求以下功能:JQuery的Ajax請求不會到達服務器
function addFormToDB(email, company, subject, text) {
var params = "email=" + email + "&company=" + company + "&subject=" + subject + "&text=" + text;
$.ajax({
url: 'http://127.0.0.1/submit',
type: 'POST',
data: '{"data":"' + params + '"}' ,
xhrFields: {
withCredentials: false
},
dataType: "jsonp",
contentType: 'text/plain',
success: function(data) {
alert("success");
},
error: function(result) {
alert("error");
}
});
}
在服務器端(node.js的+快遞)我有下面的函數處理POST請求:
app.post('/submit', function(req, res) {
console.log("enter function");
var p = new Promise(function(resolve, reject) {
db.serialize(function() {
db.run("INSERT INTO users VALUES (?, ?, ?, ?)",
[req.query['email'], req.query['company'], req.query['subject'], req.query['text']],
function (err) {
if (err) {
console.error(err);
reject();
} else {
console.log("Transaction passed");
resolve();
}
});
});
});
p.then(function(){
res.status(200).send();
}).catch(function() {
res.status(400).send();
})
});
我不知道爲什麼,但在發送POST請求,沒有任何反應,程序不進入POST請求的功能。控制檯沒有說什麼。
據我瞭解,404錯誤代碼意味着有與路由問題。然而,當客戶端的代碼是這樣(不JQuery的),它工作正常:
var params = "email=" + email + "&company=" + company + "&subject=" + subject + "&text=" + text;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://127.0.0.1:3000/submit?" + params, true);
xhttp.onreadystatechange = function() {
console.log(xhttp.readyState + " " + xhttp.status);
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log("request " + params + " was sent to DB");
alert("Thank You!");
}
};
xhttp.send();
兩個代碼段的路徑是相同的:http://127.0.0.1/submit,因此可能問題是不與路徑。
你知道這是什麼問題嗎?
你看到的'Network'選項卡上的任何東西你的調試器?你從哪裏調用'addFormToDB()'?我們可以看到客戶端的HTML嗎? –
我編輯了原文。 – CrazySynthax
404意味着它無法找到服務器上的路徑/文件....因此,我將開始尋找 – epascarello