我正在尝试使用 XMLHTTPServer 将数据发送到本地服务器。但是,我无法在服务器端接收它。
我尝试打印出传递的对象,但服务器收到的请求正文为空,即使我在使用 JSON.stringify(data)
后传递数据。服务器使用传递的数据与 AWS 上托管的 mongodb 进行通信。
浏览器端:
var cardID = 1233456789;
var data = JSON.stringify({ "Card ID": cardID });
console.log("data = " + data);
var url = `http://${serverIP}/findUser`;
var xhr = createCORSRequest("POST", url);
if (!xhr) {
alert("CORS not supported");
return;
}
xhr.onload = function() {
if (this.status == 200 && this.readyState == 4) {
userData = JSON.parse(this.responseText);
if (userData == "") {
console.log("ERROR LOADING USERS");
alert(
"USER NOT REGISTERED. Contact Michael Hofmann to Register yourself"
);
} else {
//window.location.replace('https://ha6017.github.io/link_table.html?cardid='+cardID);
console.log("userData=" + userData);
}
}
};
xhr.onerror = function() {
alert("Woops, there was an error making the request.");
};
console.log(xhr);
xhr.send(data);
服务器端:
app.post("/findUser", (req, res) => {
//console.log('req.body = ' + JSON.stringify(req.body));
var card_ID = req.body["Card ID"];
//console.log('finding user with card ID: ' + card_ID);
var que = {'Card ID': card_ID};
dbUtil.findExt("User_info", que, dbres => {
sendCORS(res, 200, dbres);
});
});
我希望来自浏览器的数据传递到服务器端。请求正文可以在req.body
card_ID
为1233456789
最佳答案
我无法复制您的代码,因为我不知道您的 createCORSRequest()
方法正在做什么。
我是这样工作的。
test.html
var cardID = 1233456789;
var data = JSON.stringify({ cardid: cardID });
console.log('data = ' + data);
var url = `http://localhost:3005/findUser`;
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (this.status == 200 && this.readyState==4) {
userData = JSON.parse(this.responseText);
if (userData == '') {
console.log('ERROR LOADING USERS');
alert('USER NOT REGISTERED. Contact Michael Hofmann to Register yourself');
} else {
//window.location.replace('https://ha6017.github.io/link_table.html?cardid='+cardID);
console.log('userData=' + userData);
}
}
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
console.log(xhr);
xhr.send(data);
server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser')
var cors = require('cors')
// use CORS
app.use(cors())
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: true
}));
// parse application/json
app.use(bodyParser.json())
app.post("/findUser", (req, res) => {
console.log('req.body = ' + JSON.stringify(req.body));
//console.log('finding user with card ID: ' + card_ID);
var que = { 'Card ID': card_ID };
/* dbUtil.findExt("User_info", que, dbres => {
sendCORS(res, 200, dbres);
});*/
});
app.listen(3005, function () {
console.log('Example app listening on port 3005!');
});
关于javascript - 如何解决浏览器端AJAX请求无法向本地服务器发送数据的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57832194/