我写的是应该从浏览器发送一个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