【问题标题】:How do I properly use xmlhttprequest to send JSON in body?如何正确使用 xmlhttprequest 在正文中发送 JSON?
【发布时间】:2019-02-08 01:17:01
【问题描述】:

我正在尝试通过 xmlhttprequest 将大量 JSON 发送到我的 Node-Express 服务器。在过去,我可以通过在 url 中编码来传递参数。我发送的 JSON 太长,无法在 url 中编码,所以我试图在正文中发送它。到目前为止,body 是一个空对象。

我读过mdn's article on xmlhttprequest.send()。 我在堆栈溢出时查看了thisthisthis,但解决方案并不能解决我的问题。

这是我的客户端代码:

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
    }

我的 node-express 服务器接收到请求,但我在请求对象的任何地方都找不到“bodystringified”的内容,这告诉我要么我没有正确构造请求对象,要么我的 api 无法正确解析请求。

我一直认为我在上面的 setRequestHeader 方法中选择了错误的内容类型。但是,我开始认为是我的服务器没有正确配置来解析请求的正文。

这是我的 Node-Express 代码的 sn-p:

const express = require('express');
const path = require('path');
require('dotenv').config({
    path: path.join(__dirname, '../.env')
  });
const bodyParser = require('body-parser');
const app = express();
const queries = require('./controllers/queries');
const os = require('os');

app.use(bodyParser.json());

app.use(express.static(path.join(__dirname, '../client/dist')));

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

以及处理这些请求的端点代码的 sn-p:

const sendData = (data, res, status) => {
    if (status) {
        res.status(status).send(data);
    } else {
        res.send(data);
    }
}

router.post('/rw_json_to_html', (req, res) => {
        console.log('req: ', req); // <-- when I inspect this obj, I can't find my json.
        let data = // do stuff with the json provided in body of req object
        sendData(data, res, 200);
}

问题: 1. 我是否错误地设置了请求标头或客户端代码中的某些内容? 2. 我是否在我的 Node-Express 选项中遗漏了一些用于正确解析请求正文的内容?例如正文解析器选项?我过去使用过 axios 并且在获取请求正文时没有问题,但是当前的应用程序要求我在客户端中使用普通的 vanilla javascript。

非常感谢您阅读我的帖子。

【问题讨论】:

  • 您的代码是从 SSL 起点还是从标准 http 开始?
  • 你好@MarcusParsons。从客户端到负载均衡器是 https,但从负载均衡器到我的节点服务器是 http。
  • 您在该节点代码中没有终点。您要在哪里查看请求正文?
  • “例如身体解析器?” — 您正在使用正文解析器。
  • @Quentin 我在帖子中添加了端点代码。感谢阅读!

标签: javascript node.js express xmlhttprequest body-parser


【解决方案1】:

当我运行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 中。

【讨论】:

  • 感谢@Quentin。我只是在我的文本编辑器中搜索我的 JSON 中的一个关键字,结果是枯燥的。这就是我克服这个问题的方法。
猜你喜欢
  • 1970-01-01
  • 2019-03-12
  • 2019-08-04
  • 2017-04-07
  • 2019-10-24
  • 2017-12-04
  • 1970-01-01
  • 2023-03-13
  • 2020-05-23
相关资源
最近更新 更多