最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

运维笔记admin6浏览0评论

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

如何正确使用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. 暂无评论