0
之前的answer需要request
組件,由於學術目的和其他相關策略,我喜歡避免使用其中的組件。香草Node.js加載8.4.0,我想:如何通過Node.js發佈JSON而不使用`request`?
var https = require('https');
var sendData = {
api_key: 'abc',
api_secret: '123',
image_url: 'http://lalala.com/123/lalala.jpg',
return_attributes: ['gender','age']
};
var options = {
hostname: 'lalala.com',
port: '443',
path: '/info',
method: 'POST',
rejectUnauthorized: false,
requestCert: true,
headers: {
'Content-Type': 'application/json',
}
};
var openreq = https.request(options, function(serverFeedback){
if (serverFeedback.statusCode == 200) {
var body = '';
serverFeedback.on('data', (data)=>{ body += data; })
.on('end',()=>{
console.log(body);
});
} else {
console.log('failed');
}
});
openreq.write(JSON.stringify(sendData))
openreq.end();
可悲的是,上面的代碼中failed
的輸出結果。
你想發送JSON到網絡服務器?您必須使用'https','request'等節點模塊才能完成這項工作,同時您可以將'data'放入'options'中,並且程序將在'req.body'中發送數據,作爲請求 – turmuka
添加錯誤處理程序:'openreq.on('error',(e)=> {console.error(e);});'知道錯誤原因。 – alexmac
那麼'serverFeedback.statusCode'是什麼? – robertklep