Tra*_*rks 182 javascript httprequest node.js express
如何从node/express中发出HTTP请求?我需要连接到另一个服务.我希望该调用是异步的,并且回调包含远程服务器响应.
bry*_*mac 209
这是我的一个样本的代码.它是异步并返回一个JSON对象.它可以做任何获取请求.请注意,有更多的最佳方式(只是一个示例) - 例如,而不是连接您放入数组并加入它的块等...希望它能让您开始朝着正确的方向前进:
const http = require('http');
const https = require('https');
/**
* getJSON: RESTful GET request returning JSON object(s)
* @param options: http options object
* @param callback: callback to pass the results JSON object(s) back
*/
module.exports.getJSON = (options, onResult) => {
console.log('rest::getJSON');
const port = options.port == 443 ? https : http;
let output = '';
const req = port.request(options, (res) => {
console.log(`${options.host} : ${res.statusCode}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
output += chunk;
});
res.on('end', () => {
let obj = JSON.parse(output);
onResult(res.statusCode, obj);
});
});
req.on('error', (err) => {
// res.send('error: ' + err.message);
});
req.end();
};
Run Code Online (Sandbox Code Playgroud)
通过创建选项对象来调用它,例如:
const options = {
host: 'somesite.com',
port: 443,
path: '/some/path',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
Run Code Online (Sandbox Code Playgroud)
并提供回调函数.
例如,在服务中,我需要上面的其余模块,然后执行此操作.
rest.getJSON(options, (statusCode, result) => {
// I could work with the resulting HTML/JSON here. I could also just return it
console.log(`onResult: (${statusCode})\n\n${JSON.stringify(result)}`);
res.statusCode = statusCode;
res.send(result);
});
Run Code Online (Sandbox Code Playgroud)
更新:
如果你正在寻找async await(线性无回调),promises,编译时支持和intellisense,我们创建一个轻量级的http和rest客户端,适合该账单:
mae*_*ics 97
尝试使用node.js中的simple http.get(options, callback)函数:
var http = require('http');
var options = {
host: 'www.google.com',
path: '/index.html'
};
var req = http.get(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
// Buffer the body entirely for processing as a whole.
var bodyChunks = [];
res.on('data', function(chunk) {
// You can process streamed parts here...
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
console.log('BODY: ' + body);
// ...and/or process the entire body here.
})
});
req.on('error', function(e) {
console.log('ERROR: ' + e.message);
});
Run Code Online (Sandbox Code Playgroud)
还有一个通用http.request(options, callback)功能,允许您指定请求方法和其他请求详细信息.
sta*_*er2 68
Request和Superagent是非常好的库.
使用request:
var request=require('request');
request.get('https://someplace',options,function(err,res,body){
if(err) //TODO: handle err
if(res.statusCode !== 200 ) //etc
//TODO Do something with response
});
Run Code Online (Sandbox Code Playgroud)
小智 31
您还可以使用Requestify,这是我为nodeJS +编写的非常酷且非常简单的HTTP客户端,它支持缓存.
只需对GET方法请求执行以下操作:
var requestify = require('requestify');
requestify.get('http://example.com/api/resource')
.then(function(response) {
// Get the response body (JSON parsed or jQuery object for XMLs)
response.getBody();
}
);
Run Code Online (Sandbox Code Playgroud)
此版本基于最初由bryanmac函数提出,该函数使用promises,更好的错误处理,并在ES6中重写.
let http = require("http"),
https = require("https");
/**
* getJSON: REST get request returning JSON object(s)
* @param options: http options object
*/
exports.getJSON = function(options)
{
console.log('rest::getJSON');
let reqHandler = +options.port === 443 ? https : http;
return new Promise((resolve, reject) => {
let req = reqHandler.request(options, (res) =>
{
let output = '';
console.log('rest::', options.host + ':' + res.statusCode);
res.setEncoding('utf8');
res.on('data', function (chunk) {
output += chunk;
});
res.on('end', () => {
try {
let obj = JSON.parse(output);
// console.log('rest::', obj);
resolve({
statusCode: res.statusCode,
data: obj
});
}
catch(err) {
console.error('rest::end', err);
reject(err);
}
});
});
req.on('error', (err) => {
console.error('rest::request', err);
reject(err);
});
req.end();
});
};
Run Code Online (Sandbox Code Playgroud)
因此,您不必传入回调函数,而是getJSON()返回一个promise.在以下示例中,该函数在ExpressJS路由处理程序中使用
router.get('/:id', (req, res, next) => {
rest.getJSON({
host: host,
path: `/posts/${req.params.id}`,
method: 'GET'
}).then(({status, data}) => {
res.json(data);
}, (error) => {
next(error);
});
});
Run Code Online (Sandbox Code Playgroud)
出错时,它将错误委托给服务器错误处理中间件.
Unirest是我从Node发出HTTP请求时遇到的最好的库.它的目标是成为一个多平台框架,因此,如果您需要在Ruby,PHP,Java,Python,Objective C,.Net或Windows 8上使用HTTP客户端,那么了解它如何在Node上工作将很有用.据我所知,unirest库主要由现有的HTTP客户端支持(例如,在Java,Apache HTTP客户端,在Node上,Mikeal的请求库) - Unirest只是将更好的API放在首位.
以下是Node.js的几个代码示例:
var unirest = require('unirest')
// GET a resource
unirest.get('http://httpbin.org/get')
.query({'foo': 'bar'})
.query({'stack': 'overflow'})
.end(function(res) {
if (res.error) {
console.log('GET error', res.error)
} else {
console.log('GET response', res.body)
}
})
// POST a form with an attached file
unirest.post('http://httpbin.org/post')
.field('foo', 'bar')
.field('stack', 'overflow')
.attach('myfile', 'examples.js')
.end(function(res) {
if (res.error) {
console.log('POST error', res.error)
} else {
console.log('POST response', res.body)
}
})
Run Code Online (Sandbox Code Playgroud)
您可以在此处直接跳转到Node文档
| 归档时间: |
|
| 查看次数: |
417866 次 |
| 最近记录: |