节点HTTPS请求 – MalformedJsonException

我试图使用节点/ HTTPS进行POST请求,但我不断收到此错误:

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

以下是启动请求的代码:

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”,这是它看起来像string:

addressTo =名称%40companyname.com&受试者=testing%20your%20email%20template&TEMPLATENAME = genericTemplate&bodyText的=此%图20是%20A%20test

我不知道我在做什么导致畸形的JSON。 我错过了什么?

你正在发送一个application/x-www-form-urlencoded有效载荷,但是告诉服务器它是application/json 。 服务器正在抱怨,因为这种不匹配。

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

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

从@mscdex中获得更多的说明

querystring.stringify返回后,您的选项对象。 否则,您将无法知道string化正文数据的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 。