如何在没有任何第三方模块的情况下在 Node Js 中发布 https 帖子?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40537749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I make a https post in Node Js without any third party module?
提问by Nova
I'm working on a project that requires https get and post methods. I've got a short https.get function working here...
我正在开发一个需要 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
});
My problem is that there's no https.post and I've already tried the http solution here with https module How to make an HTTP POST request in node.js?but returns console errors.
我的问题是没有 https.post,我已经在这里使用 https 模块尝试了 http 解决方案如何在 node.js 中发出 HTTP POST 请求?但返回控制台错误。
I've had no problem using get and post with Ajax in my browser to the same api. I can use https.get to send query information but I don't think this would be the correct way and I don't think it will work sending files later if I decide to expand.
我在浏览器中使用带有 Ajax 的 get 和 post 到同一个 api 没有问题。我可以使用 https.get 发送查询信息,但我认为这不是正确的方法,而且如果我决定扩展,我认为以后发送文件也行不通。
Is there a small example, with the minimum requirements, to make a https.request what would be a https.post if there was one? I don't want to use npm modules.
是否有一个具有最低要求的小例子来制作一个 https.request 如果有一个 https.post 会是什么?我不想使用 npm 模块。
回答by aring
For example, like this:
例如,像这样:
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();

