2017-09-25 42 views
0

我試圖做使用下面的代碼中的NodeJS一個HTTPS REST請求:創建的NodeJS HTTPS休息身體要求JSON

var querystring = require('querystring'); 
var https = require('https'); 

var postData = { 
    'Value1' : 'abc1', 
    'Value2' : 'abc2', 
    'Value3' : '3' 
}; 
var postBody = querystring.stringify(postData); 

var options = { 
    host: 'URL' 
    port: 443, 
    path: 'PATH' 
    method: 'POST', 
    headers: { 
     'Content-Type': 'application/x-www-form-urlencoded', 
     'Content-Length': postBody.length 
    } 
}; 

var req = https.request(options, function(res) { 
    console.log(res.statusCode); 
    res.on('data', function(d) { 
    process.stdout.write(d); 
    }); 
}); 
req.write(postBody); 
req.end(); 

req.on('error', function(e) { 
    console.error(e); 
}); 

請求的作品,但並不如預期。該機構將在JSON格式不發,看起來像:

RequestBody":"Value1=abc1&Value2=abc2&Value3=3

輸出應該看起來像:

RequestBody":"[\r\n {\r\n \"Value3\": \"3\",\r\n \"Value2\": \"abc2\",\r\n \"Value1\": \"abc1\"\r\n }\r\n]

我認爲這是與字符串化,也許我將它轉化以JSON格式無論如何..

回答

0

在請求的標題中指定'Content-Type': 'application/x-www-form-urlencoded'。您可以嘗試將其更改爲'Content-Type': 'application/json'

+0

這並沒有改變輸出,反正謝謝。 –

+0

我剛剛意識到您將數據作爲字符串傳遞。這不是必需的,你可以傳遞一個Object。 – Eliasib13

+0

如果我通過刪除stringify命令來嘗試這樣做,我會得到以下錯誤:TypeError:第一個參數必須是字符串或緩衝區 –

0

您需要更改內容type.try這樣

var querystring = require('querystring'); 
var https = require('https'); 

var postData = { 
    'Value1' : 'abc1', 
    'Value2' : 'abc2', 
    'Value3' : '3' 
}; 
var postBody = postData; 

var options = { 
    host: 'URL' 
    port: 443, 
    path: 'PATH' 
    method: 'POST', 
    headers: { 
     'Content-Type': 'application/json', 

    } 
}; 

var req = https.request(options, function(res) { 
    console.log(res.statusCode); 
    res.on('data', function(d) { 
    process.stdout.write(d); 
    }); 
}); 
req.write(postBody); 
req.end(); 

req.on('error', function(e) { 
    console.error(e); 
}); 
+0

與上面相同的錯誤:TypeError:第一個參數必須是字符串或Buffer –

0

我解決我的問題有以下幾點。

jsonObject = JSON.stringify({ 
    'Value1' : 'abc1', 
    'Value2' : 'abc2', 
    'Value3' : '3' 
}); 
var postheaders = { 
    'Content-Type' : 'application/json', 
    'Content-Length' : Buffer.byteLength(jsonObject, 'utf8') 
};