【问题标题】:Node HTTPS Request – MalformedJsonException节点 HTTPS 请求 – MalformedJsonException
【发布时间】:2021-03-20 10:00:12
【问题描述】:

我正在尝试使用节点/HTTPS 发出 POST 请求,但我不断收到此错误:

BODY: {"message":"MalformedJsonException: com.google.gson.stream.MalformedJsonException:使用 JsonReader.setLenient(true) 在第 1 列接受格式错误的 JSON 11 路径 $","mdcKey":""}

下面是发起请求的代码:

  const https = require('https');

  const querystring = require('querystring');

  const POSTData = querystring.stringify({
    'addressTo': 'myemail@address.com',
    'subject': 'testing your email template',
    'templateName': 'genericTemplate',
    'bodyText': 'this is a test'
  });

  console.log(POSTData);

  const HTTPOptions = {
    hostname: 'url.com',
    port: 00000,
    path: '/path',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    }
  };

  const HTTPSrequest = https.request(HTTPOptions, (response) => {
    console.log(`STATUS: ${res.statusCode}`);
    console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
    response.setEncoding('utf8');
    response.on('data', (chunk) => {
      console.log(`BODY: ${chunk}`);
    });
    response.on('end', () => {
      console.log('No more data in response.');
    });
  });

  HTTPSrequest.on('error', (error) => {
    console.log(`problem with request: ${error}`);
  });

  // write data to request body
  HTTPSrequest.write(POSTData);
  HTTPSrequest.end();

我假设 POSTData 是“格式错误的 JSON”,这就是它看起来像字符串化的样子:

addressTo=name%40companyname.com&subject=testing%20your%20email%20template&templateName=genericTemplate&bodyText=this%20is%20a%20test

我不确定我在做什么会导致格式错误的 JSON。我错过了什么?

【问题讨论】:

    标签: node.js


    【解决方案1】:

    您正在发送application/x-www-form-urlencoded 有效负载,但告诉服务器它是application/json。由于这种不匹配,服务器正在抱怨。

    简单的解决方案应该是将querystring.stringify 更改为JSON.stringify

    您可能还需要指定 Content-Length 标头,因为某些服务器可能不支持分块请求(这是节点中的默认设置)。如果确实添加了这个,请确保使用 Buffer.byteLength(POSTData) 作为标头值,而不仅仅是 POSTData.length,因为前者适用于多字节字符,而后者返回字符数(而不是字节数)。

    【讨论】:

      【解决方案2】:

      通过@mscdex 提供更多帮助

      querystring.stringify 返回后的选项对象。否则你不会知道字符串化正文数据的length

      请务必注意,您需要在选项对象中添加两个额外的标头才能发出成功的发布请求。这些是:

      'Content-Type': 'application/json',
      'Content-Length': POSTData.length
      

      检查示例:

        const HTTPOptions = {
          hostname: 'url.com',
          port: 00000,
          path: '/path',
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',          
            'Content-Length': POSTData.length
          }
        };
      

      你也可以看到这个例子:1st post

      【讨论】:

        【解决方案3】:

        JsonReader.setLenient(true) 在第 1 行第 11 列路径 $","mdcKey":""}

        接受格式错误的 JSON

        【讨论】:

        • 我认为这不是问题的根源。为什么 JSON 格式不正确?
        • 你能更清楚你建议的解决方案是什么吗?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-27
        • 2018-06-04
        • 2018-02-24
        • 2020-03-27
        • 1970-01-01
        相关资源
        最近更新 更多