最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

如何正确使用XMLHttpRequest身体发送JSON?

IT培训 admin 10浏览 0评论

如何正确使用XMLHttpRequest身体发送JSON?

我试图通过XMLHttpRequest相当大量的JSON发送到我的节点Express服务器。在过去,我已经能够通过在URL编码他们来传递参数。我送的JSON过长的URL编码,所以我试图在体内发送。到目前为止,身体是一个空的对象。

我读过mdn's article on xmlhttprequest.send()。我已经看了this,this,并在堆栈溢出this和解决方案没有解决我的问题。

这里是我的客户端代码:

var xhr = new XMLHttpRequest();
var body = {/*a javascript object with data to be sent to server*/};
var uri = 'https://my_internal_corporate_url/endpoint';
var bodyStringified = JSON.stringify(body)
xhr.open('POST', uri, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(bodyStringified);
xhr.onreadystatechange = processRequest;
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
   // do stuff with server response
    }
回答如下:

当我运行console.log('req: ', req);我得到了800线的输出,所以这也难怪,你无法找到有什么。

见the documentation for body-parser:

app.use(bodyParser.json())

app.use(function (req, res) {
  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:\n')
  res.end(JSON.stringify(req.body, null, 2))
})

解码的JSON出现在req.body

如何正确使用XMLHttpRequest身体发送JSON?

我试图通过XMLHttpRequest相当大量的JSON发送到我的节点Express服务器。在过去,我已经能够通过在URL编码他们来传递参数。我送的JSON过长的URL编码,所以我试图在体内发送。到目前为止,身体是一个空的对象。

我读过mdn's article on xmlhttprequest.send()。我已经看了this,this,并在堆栈溢出this和解决方案没有解决我的问题。

这里是我的客户端代码:

var xhr = new XMLHttpRequest();
var body = {/*a javascript object with data to be sent to server*/};
var uri = 'https://my_internal_corporate_url/endpoint';
var bodyStringified = JSON.stringify(body)
xhr.open('POST', uri, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(bodyStringified);
xhr.onreadystatechange = processRequest;
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
   // do stuff with server response
    }
回答如下:

当我运行console.log('req: ', req);我得到了800线的输出,所以这也难怪,你无法找到有什么。

见the documentation for body-parser:

app.use(bodyParser.json())

app.use(function (req, res) {
  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:\n')
  res.end(JSON.stringify(req.body, null, 2))
})

解码的JSON出现在req.body

发布评论

评论列表 (0)

  1. 暂无评论