如何在没有任何第三方模块的 NodeJs 中创建 https 文章?

我正在从事一个需要 https get 和 post 方法的项目。

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 模块 如何在 node.js 中发出 HTTP POST 请求?尝试过 http 解决方案,但是返回控制台错误。

我在浏览器中使用获取和发布 Ajax 到相同的 API 时没有问题。我可以使用 https.get 来发送查询信息,但是我不认为这是正确的方法,而且我不认为如果我决定展开它,以后发送文件会起作用。

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

167773 次浏览

For example, like this:

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();

Here's a version slightly different from the accepted answer:

  • async
  • You can pass the URL directly (no need to split to hostname, path, port)
  • It handles error HTTP status codes
  • It handles connection timeouts
  • For an alternative content type example, it sends JSON instead of 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)

In Node.js 18

Say goodbye to the node-fetch package ,axios and request ,... now the fetch API is available on the global scope by default.

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

We can make requests as we do in browsers.

For More Information

Thank goodness, node-fetch is here,

everything else is ancient history.

const fetch = require('node-fetch');
// note: use npm install node-fetch@2.0 to be able to use "require"


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....")

Job done.