我编写了一个有效的AJAX POST请求:
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();
一位同事建议使用AJAX JQuery,因此我使用JQuery编写了等效函数:
var params = "email=" + email + "&company=" + company + "&subject=" + subject + "&text=" + text;
$.ajax({
url: 'http://127.0.0.1/submit',
type: 'POST',
data: '{"data":"' + params + '"}' ,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Headers": "*"
},
contentType: 'application/json; charset=utf-8',
success: function(data) {
alert("success");
},
error: function(result) {
alert("error");
}
});
不幸的是,这个版本不起作用并发出了CORS错误:
XMLHttpRequest无法加载http://127.0.0.1/submit。回应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许来源“http://localhost:3000” 访问。
但是,请务必注意我的服务器代码包含以下行,以便修复CORS问题:
app.use(function(req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "*");
next();
});
你知道怎么解决吗?