我正在做一个需要https get和post方法的项目.我有一个简短的https.让函数在这里工作...

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.我已经在这里用https模块How to make an HTTP POST request in node.js?try 了http解决方案,但返回了控制台错误.

我在浏览器中将get和post与Ajax一起使用到同一个api没有问题.我可以使用https.开始发送查询信息,但我认为这不是正确的方法,如果我决定扩展,我认为以后发送文件也不管用.

有没有一个小例子,最低要求,使一个https.请求什么是https.如果真的有帖子?我不想使用npm模块.

推荐答案

例如,像这样:

const https = require('https');

var postData = JSON.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();

Node.js相关问答推荐

购物车是空的状态|本地存储不更新产品数量|Redux|

如何在JavaScript中使用Mongoose将项推送到MongoDB中的重嵌套数组

FiRestore UPDATE方法引发错误:&Quot;错误:13内部:收到代码为1&Quot;的RST_STREAM

如果我在 tsx 文件中使用了use client,ssr 会如何发生?

合并Shift对象数组以创建最终的排班表

Solidity 将数据位置从内存更改为存储

如何在 node /快速服务器上配置 mongoDB

错误 node :错误:绑定消息提供 16 个参数,但准备语句需要 15 个

将代码转换为 ES6 Discord.js 的问题

当我try 从本地主机发布新产品时收到错误消息

MongoDB 根据使用聚合的条件从嵌套数组中删除对象

您如何写入 aws lambda 实例的文件系统?

如何在 Node.js 的 console.log() 中创建换行符

如何获取在 NodeJS 中执行的脚本的文件名?

来自 Node-aws 的 Dynamo Local:所有操作都失败无法对不存在的表执行操作

如何在 Mongoose 模式中设置数组大小限制

node 应用程序是否有任何独立的 gui 模块

Selenium WebDriver 等到元素显示

当我try 向我的 S3 存储桶 (Node.js) 发送内容时,AWS 缺少凭证

在 Node.js 上使用 Connect 无法获取 /