如何在 node.js 中发出 HTTP POST 请求?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6158933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How is an HTTP POST request made in node.js?
提问by Mark
How can I make an outbound HTTP POST request, with data, in node.js?
如何在 node.js 中使用数据发出出站 HTTP POST 请求?
采纳答案by onteria_
Here's an example of using node.js to make a POST request to the Google Compiler API:
以下是使用 node.js 向 Google Compiler 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);
}
});
I've updated the code to show how to post data from a file, instead of the hardcoded string. It uses the async fs.readFilecommand to achieve this, posting the actual code after a successful read. If there's an error, it is thrown, and if there's no data the process exits with a negative value to indicate failure.
我更新了代码以展示如何从文件而不是硬编码字符串发布数据。它使用 asyncfs.readFile命令来实现这一点,在成功读取后发布实际代码。如果出现错误,则抛出该错误,如果没有数据,则进程以负值退出以指示失败。
回答by Jed Watson
This gets a lot easier if you use the requestlibrary.
如果您使用请求库,这会变得容易得多。
var request = require('request');
request.post(
'http://www.yoursite.com/formpage',
{ json: { key: 'value' } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
);
Aside from providing a nice syntax it makes json requests easy, handles oauth signing (for twitter, etc.), can do multi-part forms (e.g. for uploading files) and streaming.
除了提供良好的语法之外,它还使 json 请求变得简单,处理 oauth 签名(用于 twitter 等),可以执行多部分表单(例如用于上传文件)和流式传输。
To install request use command npm install request
安装请求使用命令 npm install request
回答by Josiah Choi
You can use request library. https://www.npmjs.com/package/request
您可以使用请求库。https://www.npmjs.com/package/request
var request = require('request');
To post JSON data:
要发布 JSON 数据:
var myJSONObject = { ... };
request({
url: "http://josiahchoi.com/myjson",
method: "POST",
json: true, // <--Very important!!!
body: myJSONObject
}, function (error, response, body){
console.log(response);
});
To post xml data:
要发布 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);
});
回答by Grant Li
I use Restlerand Needlefor production purposes. They are both much more powerful than native httprequest. It is possible to request with basic authentication, special header entry or even upload/download files.
我将Restler和Needle用于生产目的。它们都比原生 httprequest 强大得多。可以使用基本身份验证、特殊标头条目甚至上传/下载文件进行请求。
As for post/get operation, they also are much simpler to use than raw ajax calls using httprequest.
至于 post/get 操作,它们也比使用 httprequest 的原始 ajax 调用简单得多。
needle.post('https://my.app.com/endpoint', {foo:'bar'},
function(err, resp, body){
console.log(body);
});
回答by mpen
Simple and dependency-free. Uses a Promise so that you can await the result. It returns the response body and does not check the response status code.
简单且无依赖。使用 Promise 以便您可以等待结果。它返回响应正文并且不检查响应状态代码。
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 body = Buffer.concat(chunks);
switch(res.headers['content-type']) {
case 'application/json':
body = JSON.parse(body);
break;
}
resolve(body)
})
})
req.on('error',reject);
if(body) {
req.write(body);
}
req.end();
})
}
Usage:
用法:
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',
})
})
回答by ranm8
You can also use Requestify, a really cool and simple HTTP client I wrote for nodeJS + it supports caching.
您还可以使用Requestify,这是我为 nodeJS 编写的一个非常酷且简单的 HTTP 客户端,它支持缓存。
Just do the following:
只需执行以下操作:
var requestify = require('requestify');
requestify.post('http://example.com', {
hello: 'world'
})
.then(function(response) {
// Get the response body (JSON parsed or jQuery object for XMLs)
response.getBody();
});
回答by Levi Roberts
Update 2020:
2020 年更新:
I've been really enjoying phin- The ultra-lightweight Node.js HTTP client
我一直很喜欢phin-超轻量级的 Node.js HTTP 客户端
It can be used in two different ways. One with Promises (Async/Await) and the other with traditional callback styles.
它可以以两种不同的方式使用。一种带有 Promises (Async/Await),另一种带有传统的回调风格。
Install via: npm i phin
通过以下方式安装: npm i phin
Straight from it's README with await:
直接来自它的自述文件await:
const p = require('phin')
await p({
url: 'https://ethanent.me',
method: 'POST',
data: {
hey: 'hi'
}
})
Unpromisifed (callback) style:
未承诺(回调)样式:
const p = require('phin').unpromisified
p('https://ethanent.me', (err, res) => {
if (!err) console.log(res.body)
})
As of 2015there are now a wide variety of different libraries that can accomplish this with minimal coding. I much prefer elegant light weight libraries for HTTP requests unless you absolutely need control of the low level HTTP stuff.
截至2015 年,现在有多种不同的库可以通过最少的编码实现这一点。我更喜欢优雅的轻量级 HTTP 请求库,除非您绝对需要控制低级 HTTP 内容。
One such library is Unirest
Unirest就是这样的一个库
To install it, use npm. $ npm install unirest
要安装它,请使用npm.$ npm install unirest
And onto the Hello, World!example that everyone is accustomed to.
并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);
});
Extra:
A lot of people are also suggesting the use of request[ 2 ]
It should be worth noting that behind the scenes Unirestuses the requestlibrary.
值得注意的是,幕后Unirest使用了该request库。
Unirest provides methods for accessing the request object directly.
Unirest 提供了直接访问请求对象的方法。
Example:
例子:
var Request = unirest.get('http://mockbin.com/request');
回答by Giulio Roggero
var https = require('https');
/**
* HOW TO Make an HTTP Call - POST
*/
// do a POST request
// create the JSON object
jsonObject = JSON.stringify({
"message" : "The web of things is approaching, let do some tests to be ready!",
"name" : "Test message posted with node.js",
"caption" : "Some tests with node.js",
"link" : "http://www.youscada.com",
"description" : "this is a description",
"picture" : "http://youscada.com/wp-content/uploads/2012/05/logo2.png",
"actions" : [ {
"name" : "youSCADA",
"link" : "http://www.youscada.com"
} ]
});
// prepare the header
var postheaders = {
'Content-Type' : 'application/json',
'Content-Length' : Buffer.byteLength(jsonObject, 'utf8')
};
// the post options
var optionspost = {
host : 'graph.facebook.com',
port : 443,
path : '/youscada/feed?access_token=your_api_key',
method : 'POST',
headers : postheaders
};
console.info('Options prepared:');
console.info(optionspost);
console.info('Do the POST call');
// do the POST call
var reqPost = https.request(optionspost, function(res) {
console.log("statusCode: ", res.statusCode);
// uncomment it for header details
// console.log("headers: ", res.headers);
res.on('data', function(d) {
console.info('POST result:\n');
process.stdout.write(d);
console.info('\n\nPOST completed');
});
});
// write the json data
reqPost.write(jsonObject);
reqPost.end();
reqPost.on('error', function(e) {
console.error(e);
});
回答by attacomsian
There are dozens of open-source libraries available that you can use to making an HTTP POST request in Node.
有许多可用的开源库可用于在 Node.js 中发出 HTTP POST 请求。
1. Axios(Recommended)
1. Axios(推荐)
const axios = require('axios');
const data = {
name: 'John Doe',
job: 'Content Writer'
};
axios.post('https://reqres.in/api/users', data)
.then((res) => {
console.log(`Status: ${res.status}`);
console.log('Body: ', res.data);
}).catch((err) => {
console.error(err);
});
2. Needle
2.针
const needle = require('needle');
const data = {
name: 'John Doe',
job: 'Content Writer'
};
needle('post', 'https://reqres.in/api/users', data, {json: true})
.then((res) => {
console.log(`Status: ${res.statusCode}`);
console.log('Body: ', res.body);
}).catch((err) => {
console.error(err);
});
3. Request
3.请求
const request = require('request');
const options = {
url: 'https://reqres.in/api/users',
json: true,
body: {
name: 'John Doe',
job: 'Content Writer'
}
};
request.post(options, (err, res, body) => {
if (err) {
return console.log(err);
}
console.log(`Status: ${res.statusCode}`);
console.log(body);
});
4. Native HTTPS Module
4.原生HTTPS模块
const https = require('https');
const data = JSON.stringify({
name: 'John Doe',
job: 'Content Writer'
});
const options = {
hostname: 'reqres.in',
path: '/api/users',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
};
const req = https.request(options, (res) => {
let data = '';
console.log('Status Code:', res.statusCode);
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('Body: ', JSON.parse(data));
});
}).on("error", (err) => {
console.log("Error: ", err.message);
});
req.write(data);
req.end();
For details, check out this article.
有关详细信息,请查看这篇文章。
回答by Piyush Sagar
This is the simplest way I use to make request: using 'request' module.
这是我用来发出请求的最简单的方法:使用“请求”模块。
Command to install 'request' module :
安装“请求”模块的命令:
$ npm install request
Example code:
示例代码:
var request = require('request')
var options = {
method: 'post',
body: postData, // Javascript object
json: true, // Use,If you are sending JSON data
url: url,
headers: {
// Specify headers, If any
}
}
request(options, function (err, res, body) {
if (err) {
console.log('Error :', err)
return
}
console.log(' Body :', body)
});
You can also use Node.js's built-in 'http' module to make request.
您还可以使用 Node.js 的内置“http”模块来发出请求。

