我正在研究一个需要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。post和我已经尝试了http解决方案在这里与https模块如何使一个http post请求在node.js?但是返回控制台错误。
我已经没有问题使用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();
这是一个与公认答案略有不同的版本:
- @returns
Promise
- 你可以直接传递URL(不需要拆分到主机名,路径,端口)
- 处理HTTP状态码错误
- 处理连接超时
- 对于另一个内容类型示例,它发送JSON而不是
x-www-form-urlencoded
const https = require('https')
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
告别节点获取包,axios和请求,…现在,默认情况下,fetch API在全局作用域中是可用的。
POST请求
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')
})
GET请求
const res = await fetch('https://nodejs.org/api/documentation.json');
if (res.ok) {
const data = await res.json();
console.log(data);
}
我们可以像在浏览器中那样发出请求。
查看更多信息
谢天谢地,这里有节点获取,
其他的都是古老的历史。
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....")
工作。