我如何能使出站HTTP POST请求,与数据,在node.js?
当前回答
简单且无依赖。使用承诺,让你可以等待结果。它返回响应体,不检查响应状态代码。
const https = require('https');
function httpsPost({body, ...options}) {
return new Promise((resolve,reject) => {
const req = https.request({
method: 'POST',
...options,
}, res => {
const chunks = [];
res.on('data', data => chunks.push(data))
res.on('end', () => {
let resBody = Buffer.concat(chunks);
switch(res.headers['content-type']) {
case 'application/json':
resBody = JSON.parse(resBody);
break;
}
resolve(resBody)
})
})
req.on('error',reject);
if(body) {
req.write(body);
}
req.end();
})
}
用法:
async function main() {
const res = await httpsPost({
hostname: 'sentry.io',
path: `/api/0/organizations/org/releases/${changesetId}/deploys/`,
headers: {
'Authorization': `Bearer ${process.env.SENTRY_AUTH_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
environment: isLive ? 'production' : 'demo',
})
})
}
main().catch(err => {
console.log(err)
})
其他回答
您可以使用请求库。https://www.npmjs.com/package/request
var request = require('request');
要发布JSON数据:
var myJSONObject = { ... };
request({
url: "http://josiahchoi.com/myjson",
method: "POST",
json: true, // <--Very important!!!
body: myJSONObject
}, function (error, response, body){
console.log(response);
});
要发布xml数据:
var myXMLText = '<xml>...........</xml>'
request({
url: "http://josiahchoi.com/myjson",
method: "POST",
headers: {
"content-type": "application/xml", // <--Very important!!!
},
body: myXMLText
}, function (error, response, body){
console.log(response);
});
编辑:截至2020年2月,请求已弃用。
在Node.js 18
跟节点获取包、axios和request说再见吧……现在默认情况下,全局作用域中的获取API是可用的。
const res = await fetch('https://nodejs.org/api/documentation.json');
if (res.ok) {
const data = await res.json();
console.log(data);
}
我们可以像在浏览器中那样发出请求。
更多信息
2020年更新:
我真的很喜欢phin -超轻量级的Node.js HTTP客户端
它有两种不同的用法。一个是promise (Async/Await),另一个是传统的回调样式。
安装通过:npm i phin
直接从它的README等待:
const p = require('phin')
await p({
url: 'https://ethanent.me',
method: 'POST',
data: {
hey: 'hi'
}
})
未承诺(回调)风格:
const p = require('phin').unpromisified
p('https://ethanent.me', (err, res) => {
if (!err) console.log(res.body)
})
截至2015年,现在有很多不同的库可以用最少的代码实现这一点。我更喜欢优雅的轻量级HTTP请求库,除非你绝对需要控制低级HTTP的东西。
Unirest就是这样一个库
要安装它,使用npm。 $ NPM安装unirest
然后是Hello, World!大家都熟悉的例子。
var unirest = require('unirest');
unirest.post('http://example.com/helloworld')
.header('Accept', 'application/json')
.send({ "Hello": "World!" })
.end(function (response) {
console.log(response.body);
});
额外的: 很多人还建议使用请求[2]
值得注意的是,Unirest在幕后使用的是请求库。
Unirest提供了直接访问请求对象的方法。
例子:
var Request = unirest.get('http://mockbin.com/request');
如果您需要XML请求,我将与axios库共享我的代码。
const {default: axios} = require('axios');
let xmlString = '<XML>...</XML>';
axios.post('yourURL', xmlString)
.then((res) => {
console.log("Status: ", res.status);
console.log("Body: ", res.data);
})
.catch((err) => {
console.error("Error: ", err);
});
下面是一个使用node.js向谷歌编译器API发出POST请求的例子:
// We need this to build our post string
var querystring = require('querystring');
var http = require('http');
var fs = require('fs');
function PostCode(codestring) {
// Build the post string from an object
var post_data = querystring.stringify({
'compilation_level' : 'ADVANCED_OPTIMIZATIONS',
'output_format': 'json',
'output_info': 'compiled_code',
'warning_level' : 'QUIET',
'js_code' : codestring
});
// An object of options to indicate where to post to
var post_options = {
host: 'closure-compiler.appspot.com',
port: '80',
path: '/compile',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(post_data)
}
};
// Set up the request
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
});
});
// post the data
post_req.write(post_data);
post_req.end();
}
// This is an async file read
fs.readFile('LinkedList.js', 'utf-8', function (err, data) {
if (err) {
// If this were just a small part of the application, you would
// want to handle this differently, maybe throwing an exception
// for the caller to handle. Since the file is absolutely essential
// to the program's functionality, we're going to exit with a fatal
// error instead.
console.log("FATAL An error occurred trying to read in the file: " + err);
process.exit(-2);
}
// Make sure there's data before we post it
if(data) {
PostCode(data);
}
else {
console.log("No data to post");
process.exit(-1);
}
});
我已经更新了代码,以展示如何从文件中发布数据,而不是硬编码的字符串。它使用异步文件系统。readFile命令来实现这一点,在成功读取后发布实际代码。如果出现错误,则抛出错误,如果没有数据,则进程退出,并显示一个负值以指示失败。
推荐文章
- 有没有办法修复包锁。json lockfileVersion所以npm使用特定的格式?
- 如何使用npm全局安装一个模块?
- 实时http流到HTML5视频客户端的最佳方法
- 什么是HTTP中的“406-不可接受的响应”?
- 使用node.js下载图像
- Node.js Express中的HTTP GET请求
- Node.js:将文本文件读入数组。(每一行都是数组中的一项。)
- 最好的轻量级web服务器(只有静态内容)的Windows
- npm犯错!错误:EPERM:操作不允许,重命名
- Node Sass还不支持当前环境:Linux 64位,带false
- 我如何添加环境变量启动。VSCode中的json
- HTTP POST在Java中使用JSON
- Chrome中的请求监控
- 解析错误:无法读取文件“…/tsconfig.json”.eslint
- 在Node.js中'use strict'语句是如何解释的?