[英]How to post JSON via Node.js without using `request`?
The previous answer requires the request
component, of which I like to avoid using, due to academic purpose and other related policy. 上一个答案需要request
组件,由于学术目的和其他相关政策,我希望避免使用该组件。 With vanilla Node.js 8.4.0, I tried: 使用香草Node.js 8.4.0,我尝试:
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();
Sadly the code above results in failed
output. 不幸的是,上面的代码导致输出failed
。
There is nothing wrong with your request flow, as it almost exactly resembles Node.js documentation HTTP and HTTPS guides (apart from JSON
Content-Type). 您的请求流程没有任何问题,因为它几乎完全类似于Node.js文档的HTTP和HTTPS指南(除JSON
Content-Type外)。 However, you're only looking for 200
response and not expecting that error could have message in body that should be captured before serverFeedback.statusCode == 200
condition: 但是,您只想查找200
响应,并不期望该错误可能在主体中包含应在serverFeedback.statusCode == 200
条件之前捕获的消息:
serverFeedback.setEncoding('utf8');
serverFeedback.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
serverFeedback.on('end', () => {
console.log('No more data in response.');
});
In any case, problem is definitely with the remote host then, and you could also observe response information more closely with: 无论如何,问题肯定出在远程主机上,您还可以通过以下方式更仔细地观察响应信息:
console.log(`STATUS: ${serverFeedback.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(serverFeedback.headers)}`);
Just one more thing, if you're using version 8 , for the same academic purposes it's worth reconsidering utilization of var
in favor of let
& const
, as well as fat arrow functions and Promises instead of callbacks. 再说一件事,如果您使用版本8 ,出于相同的学术目的,则值得重新考虑使用var
,而支持let
& const
,以及胖箭头函数和Promises而不是回调。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.