我编写了以下函数,该函数应该从浏览器发送 AJAX POST 请求:
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 + express)我有以下处理 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 ,所以问题可能不在于路径。
你知道问题出在哪里吗?
最佳答案
您的问题是您正在进行 JSONP 调用,这是一个 GET 请求。您不能将 JSONP 设为 POST。查看屏幕截图中的请求,您可以看到它是一个 GET。
dataType: "jsonp", <-- changes the POST to a GET
JSONP 的工作原理是粘贴 <script>
页面上的标记,因此它是 GET。所以最终 Ajax 和普通 JavaScript 是不一样的。纯 JavaScript 是将脚本标记附加到页面。
关于javascript - JQuery Ajax 请求未到达服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41344196/