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();
});
18
To Post Rest/JSON Request 我们可以简单地使用请求包并保存我们必须在Json变量中发送的值 .
首先在 npm install request --save 的控制台中安装require包
var request = require('request');
var options={
'key':'28',
'key1':'value',
'key2':'value'
}
request({
url:"http://dev.api.ean.com/ean-services/rs/hotel/v3/ping?
minorRev="+options.key+
"&cid="+options.key1+
"&apiKey="+options.key2,
method:"POST",
json:true},function(error,response,body){
console.log(body)
}
);
request.on('timeout', function () {
// Timeout happend. Server received request, but not handled it
// (i.e. doesn't send any response or it took to long).
// You don't know what happend.
// It will emit 'error' message as well (with ECONNRESET code).
req.abort();
if(timeout) return timeout( new Error('request timed out') );
});
我强烈建议注册两个处理程序 .
响应主体是分块的,因此您必须在 data 处理程序中连接块:
var body = '';
response.on('data', function(d) {
body += d;
});
const http = require("http")
const https = require("https")
// Request handler function
let postJSON = (options, postData, callback) => {
// Serializing JSON
post_data = JSON.stringify(postData)
let port = options.port == 443 ? https : http
// Callback function for the request
let req = port.request(options, (res) => {
let output = ''
res.setEncoding('utf8')
// Listener to receive data
res.on('data', (chunk) => {
output += chunk
});
// Listener for intializing callback after receiving complete response
res.on('end', () => {
let obj = JSON.parse(output)
callback(res.statusCode, obj)
});
});
// Handle any errors occurred while making request
req.on('error', (err) => {
//res.send('error: ' + err.message)
});
// Request is made here, with data as string or buffer
req.write(post_data)
// Ending the request
req.end()
};
let callPost = () => {
let data = {
'name': 'Jon',
'message': 'hello, world'
}
let options = {
host: 'domain.name', // Your domain name
port: 443, // 443 for https and 80 for http
path: '/path/to/resource', // Path for the request
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)
}
}
postJSON(options, data, (statusCode, result) => {
// Handle response
// Process the received data
});
}
6
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);
});
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)
});
您还可以使用Node.js的内置“http”模块发出请求 .
3
以下是使用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);
}
});
我已更新代码以显示如何从文件发布数据,而不是硬编码字符串 . 它使用async fs.readFile 命令来实现此目的,在成功读取后发布实际代码 . 如果's an error, it is thrown, and if there'没有数据,则进程以负值退出以指示失败 .
18 回答
简单且无依赖性 . 使用Promise以便等待结果 . 它返回响应主体,不检查响应状态代码 .
用法:
我喜欢superagent的简单性(https://github.com/visionmedia/superagent) . 节点和浏览器上的api相同 .
2018编辑:最近,我已经开始使用node-fetch(https://www.npmjs.com/package/node-fetch),它的api与浏览器中的
fetch
匹配 .您还可以使用Requestify,这是我为nodeJS编写的非常酷且简单的HTTP客户端,它支持缓存 .
只需执行以下操作:
To Post Rest/JSON Request
我们可以简单地使用请求包并保存我们必须在Json变量中发送的值 .
首先在 npm install request --save 的控制台中安装require包
您可以使用请求库 . https://www.npmjs.com/package/request
要发布JSON数据:
要发布xml数据:
这是我对
POST
和GET
的解决方案 .About the Post method:
如果正文是JSON对象,那么使用
JSON.stringify
对其进行反序列化很重要,并可能相应地设置Content-Lenght
标头:在将其写入请求之前:
About both Get and Post methods:
timeout
可以作为socket
断开连接发生,因此您必须注册其处理程序,如:而
request
处理程序是我强烈建议注册两个处理程序 .
响应主体是分块的,因此您必须在
data
处理程序中连接块:在
end
body
将包含整个响应正文:用
try
... catchthe
JSON.parse`包装是安全的,因为你不能确定它实际上是格式良好的json,并且在你做请求时无法确定它 .Module: SimpleAPI
Usage:
发布使用其他配置选项和自定义标头的axios.post请求的另一个axios示例 .
通过使用request依赖 .
简单解决方案
在创建一个低级实用程序来处理帖子并获得我的项目请求之后经过很多努力之后,我决定在这里发布我的努力 . 就接受的答案而言,这里有一个用于发送http和https POST请求以发送JSON数据的片段 .
我找到了一个视频,解释了如何实现这个目标:https://www.youtube.com/watch?v=nuw48-u3Yrg
它使用默认的“http”模块以及“querystring”和“stringbuilder”模块 . 应用程序从网页中获取两个数字(使用两个文本框),并在提交时返回这两个数字的总和(以及保留文本框中的值) . 这是我在其他地方找到的最好的例子 .
或者你可以另一个图书馆:
我使用Restler和Needle进行制作 . 它们比原生的httprequest强大得多 . 可以通过基本认证,特殊 Headers 输入或甚至上传/下载文件来请求 .
至于post / get操作,它们比使用httprequest的原始ajax调用更简单 .
这是我用来发出请求的最简单方法:使用'request'模块 .
用于安装“请求”模块的命令:
示例代码:
您还可以使用Node.js的内置“http”模块发出请求 .
以下是使用node.js向Google Compiler API发出POST请求的示例:
我已更新代码以显示如何从文件发布数据,而不是硬编码字符串 . 它使用async
fs.readFile
命令来实现此目的,在成功读取后发布实际代码 . 如果's an error, it is thrown, and if there'没有数据,则进程以负值退出以指示失败 .对于那些晚年来到这里的人 . 现在有各种不同的库可以用最少的编码来实现这一点 . 除非你绝对需要控制低级HTTP的东西,否则我更喜欢优雅的轻量级库来处理HTTP请求 .
一个这样的图书馆是Unirest
要安装它,请使用
npm
.$ npm install unirest
并且在每个人都习惯的
Hello, World!
示例上 .Extra:
很多人也建议使用request [ 2 ]
值得注意的是,幕后
Unirest
使用request
库 .Unirest提供直接访问请求对象的方法 .
Example:
如果使用request库,这会变得更容易 .
除了提供一个很好的语法,它使json请求变得容易,处理oauth签名(对于twitter等),可以做多部分表单(例如用于上传文件)和流式传输 .
要安装请求,请使用命令
npm install request
如果您正在寻找基于承诺的HTTP请求,axios可以很好地完成其工作 .