2017-04-14 99 views
1

我试图用使一个POST请求节点/ HTTPS,但我不断收到此错误:节点HTTPS请求 - MalformedJsonException

BODY: {"message":"MalformedJsonException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 11 path $","mdcKey":""}

这里的发起请求的代码:

const https = require('https'); 

    const querystring = require('querystring'); 

    const POSTData = querystring.stringify({ 
    'addressTo': '[email protected]', 
    '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。我错过了什么?

回答

2

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

简单的解决方案应该是只是改变querystring.stringifyJSON.stringify

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

+0

修复它,谢谢你的答案! – timothym

1

帮助更多与阐释从@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