2017-04-14 71 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