我正在一个需要https get和post方法的项目中。我有一个简短的https.get函数在这里工作...
const https = require("https");
function get(url, callback) {
"use-strict";
https.get(url, function (result) {
var dataQueue = "";
result.on("data", function (dataBuffer) {
dataQueue += dataBuffer;
});
result.on("end", function () {
callback(dataQueue);
});
});
}
get("https://example.com/method", function (data) {
// do something with data
});
我的问题是没有https.post,我已经在这里使用https模块尝试了http解决方案。如何在node.js中发出HTTP POST请求?但返回控制台错误。
我在浏览器中使用get和post与Ajax到相同的api都没有问题。我可以使用https.get来发送查询信息,但是我认为这不是正确的方法,并且如果我决定扩展的话,我认为它不会在以后发送文件。
有没有一个最低要求的小示例,可以发出一个https.request如果存在一个https.post,它将是什么?我不想使用npm模块。
例如,像这样:
const querystring = require('querystring');
const https = require('https');
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: 'posttestserver.com',
port: 443,
path: '/post.php',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.write(postData);
req.end();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句