如何在没有任何第三方模块的Node Js中发布https帖子?

Nov*_*ova 42 https post node.js

我正在开发一个需要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
});
Run Code Online (Sandbox Code Playgroud)

我的问题是没有https.post,我已经在这里用https模块尝试了http解决方案如何在node.js中发出HTTP POST请求?但返回控制台错误.

我在浏览器中使用Ajax和Ajax发布到同一个api时没有问题.我可以使用https.get来发送查询信息,但我认为这不是正确的方法,如果我决定扩展,我认为它不会在以后发送文件.

是否有一个小的例子,有最低要求,使https.request成为https.post,如果有的话?我不想使用npm模块.

ari*_*ing 113

例如,像这样:

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();
Run Code Online (Sandbox Code Playgroud)

  • 很好的回答@aring.如果要发送JSON,请更改以下内容:```var postData = JSON.stringify({msg:'Hello World!'})```和```'Content-Type':'application/json'` `` (26认同)
  • 我假设“req.write(postData);”将是数据的发布,我是正确的吗?我有从发布位置返回的数据,并在终端中以 JSON 格式获取输出数据。我如何才能将该数据保存到我从中返回的变量中? (4认同)

Abo*_*zlR 20

在 Node.js 18 及更高版本中

告别node-fetch 包axiosrequest ……现在fetch API 默认在全局范围内可用

发布请求

app.get('/', (req, res, next) => {
    // Make a post Request.
    
    fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        body: JSON.stringify({
            title: 'foo',
            body: 'bar',
            userId: 1,
        }),
        headers: {
            'Content-type': 'application/json; charset=UTF-8',
        },
    })
        .then((response) => response.json())
        .then((json) => console.log(json))
        .catch(error => {
            console.log(error)
        })

    res.send('Fetch API is available on the global scope by default')
})
Run Code Online (Sandbox Code Playgroud)

获取请求

const res = await fetch('https://nodejs.org/api/documentation.json');
if (res.ok) {
  const data = await res.json();
  console.log(data);
}
Run Code Online (Sandbox Code Playgroud)

我们可以像在浏览器中一样发出请求。

了解更多信息


max*_*x_i 5

这是一个与接受的答案略有不同的版本:

  • async
  • 可以直接传递URL(无需拆分为主机名、路径、端口)
  • 它处理错误 HTTP 状态代码
  • 它处理连接超时
  • 对于替代内容类型示例,它发送 JSON 而不是 x-www-form-urlencoded
const https = require('https')

async function post(url, data) {
  const dataString = JSON.stringify(data)

  const options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': dataString.length,
    },
    timeout: 1000, // in ms
  }

  return new Promise((resolve, reject) => {
    const req = https.request(url, options, (res) => {
      if (res.statusCode < 200 || res.statusCode > 299) {
        return reject(new Error(`HTTP status code ${res.statusCode}`))
      }

      const body = []
      res.on('data', (chunk) => body.push(chunk))
      res.on('end', () => {
        const resString = Buffer.concat(body).toString()
        resolve(resString)
      })
    })

    req.on('error', (err) => {
      reject(err)
    })

    req.on('timeout', () => {
      req.destroy()
      reject(new Error('Request time out'))
    })

    req.write(dataString)
    req.end()
  })
}

const res = await post('https://...', data)
Run Code Online (Sandbox Code Playgroud)


Fat*_*tie 5

对于 Node.js 18 及更高版本,“fetch”是标准的。

Node 16 刚刚结束生命,所以一切

否则就是古老的历史

console.log("trying ...")

let body = {
    "ids": ["4e4e4e4e-4e4e-4e4e-4e4e-4e4e4e4e4e4e"]
};

fetch('https://blahblah.com/blah', {
    method: 'POST',
    body: JSON.stringify(body),
    headers: {
        'accept': 'application/json',
        'x-api-key': 'superamazingsecretcryptostuff',
        'Content-Type': 'application/json'
        // fyi, NO need for content length
    }
})
    .then(res => res.json())
    .then(json => console.log(json))
    .catch (err => console.log(err))

console.log("done....")
Run Code Online (Sandbox Code Playgroud)

任务完成。

  • 问题不是专门关于在没有任何第三方模块的情况下执行此操作吗? (3认同)
  • @Fattie - 您不能简单地在答案中添加另一个答案而不指定他/她的名字。/sf/ask/2837642461/#71991926 (2认同)