【问题标题】:How to receive data with node如何使用节点接收数据
【发布时间】:2019-07-16 18:17:18
【问题描述】:

我正在开发网站的前端和后端。我尝试将数据发送到我的后端,但我似乎无法以任何方式解析它。我正在使用 node.js 和 express 来构建后端。我不明白如何从我的网站访问我发送的数据。

这就是我将数据发送到服务器的方式。我检查并在发送数据时正确发送为有效的 json。

function submitForm(){
  name = document.getElementById('customer_name1').value;
  parent_name = document.getElementById('parent_name').value;
  smyID = document.getElementById('symID');
  customer_id = uuidv4();
  loc1 = document.getElementById('loc1').value;
  location_id = uuidv4();
  r_name = document.getElementById('room_name');
  r_symID = document.getElementById('rsym_id');
  room_id = uuidv4();
  d_e164 = document.getElementById('e164').value;
  username = document.getElementById('u_name').value;
  user_password = document.getElementById('u_pass');
  ip_adr = document.getElementById('ip_adr').value;
  device_id = uuidv4();
  var customer = {
    customer_name: [name, customer_id, parent_name, symID],
    locations: [loc1, location_id, customer_id],
    rooms: [r_name, room_id, location_id, r_symID],
    devices: [room_id, d_e164, username, user_password, ip_adr, device_id]
  };
  var data = JSON.stringify(customer);
  var xhttp;
  if (window.XMLHttpRequest){
      xhttp=new XMLHttpRequest();
  }
  else{
      xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

  xhttp.open("post", 'http://localhost:3000/users', true);
  xhttp.setRequestHeader('Content-type', 'application/application/json;charset=UTF-8');
  xhttp.send(data);

我之前有一个版本,我可以在其中获取我想要的数据,但我想进行一次 api 调用而不是 5 个不同的调用来执行此操作。这是以前的工作。

function createUser(req, res, next) {
  let user_id = uuidv4();
  let new_customer = new PQ('insert into customer(customer_name, ID, parent, symID) values ($1, $2, $3, $4)');
  new_customer.values = [req.body.customer_name, user_id, req.body.parent, req.body.symID];
  db.none(new_customer)
    .then(() => {
      res.status(200).json({
        id: user_id
      })
    })
    .catch(function (err) {
      return next(err);
  });
}

当我尝试将任何内容发布到服务时,我只会收到 500 错误。没有其他任何类型的描述。

更新:当我尝试使用 console.log 做一个简单的功能时,我使用 send 方法时没有发送任何数据!

【问题讨论】:

  • 你在使用 express.js 吗?
  • 是的,我正在使用快递

标签: javascript node.js json


【解决方案1】:

你试过 console.log() 这些值吗

req.body.customer_name、user_id、req.body.parent、req.body.symID

在服务器上?只是看看你能不能得到那些。

也许尝试使用 JSON.parse() 将正文解析回 json

【讨论】:

  • 好的,然后也许尝试做 JSON.parse(req.body) 并将其放入另一个变量中,并在您设置新客户值时使用该变量
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-05
相关资源
最近更新 更多