javascript - 如何解决浏览器端AJAX请求无法向本地服务器发送数据的问题?

标签 javascript node.js ajax express

我正在尝试使用 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_ID1233456789

最佳答案

我无法复制您的代码,因为我不知道您的 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/

相关文章:

javascript - 如何在不重新加载 DOM 的情况下保持表单更新?

javascript - 连接 javascript 事件并传递参数

javascript - 如何使输入在焦点上有文本?

javascript - 根据 jQuery 中的文本框值 onload 更改 CSS 样式?

javascript - NodeJS、Javascript 聊天;对于每个数组

html - 在 res.sendfile express js 上发送 html 和 css 文件

Python Gae Ajax,如何实现通知?

Javascript 为什么 Number 和 ParseFloat 在相加数字时都会创建一个长数字?

node.js - Linux 中的 HtmlWebpackPlugin 未生成索引 html 文件

php - 无法将 ajax 填充的字段传递给 php