如何从Node.js或Express.js中发出HTTP请求?我需要连接到另一个服务。我希望调用是异步的,并且回调包含远程服务器的响应。
当前回答
## you can use request module and promise in express to make any request ##
const promise = require('promise');
const requestModule = require('request');
const curlRequest =(requestOption) =>{
return new Promise((resolve, reject)=> {
requestModule(requestOption, (error, response, body) => {
try {
if (error) {
throw error;
}
if (body) {
try {
body = (body) ? JSON.parse(body) : body;
resolve(body);
}catch(error){
resolve(body);
}
} else {
throw new Error('something wrong');
}
} catch (error) {
reject(error);
}
})
})
};
const option = {
url : uri,
method : "GET",
headers : {
}
};
curlRequest(option).then((data)=>{
}).catch((err)=>{
})
其他回答
使用reqclient:不是为脚本目的设计的 像request或者其他库。Reqclient允许在构造函数中使用 在需要重用时指定许多有用的配置 配置一次又一次:基本URL,头,认证选项, 日志记录选项,缓存等。也有有用的功能,如 查询和URL解析,自动查询编码和JSON解析等。
使用库的最佳方法是创建一个模块来导出对象 指向API和需要连接的必要配置:
模块client.js:
let RequestClient = require("reqclient").RequestClient
let client = new RequestClient({
baseUrl: "https://myapp.com/api/v1",
cache: true,
auth: {user: "admin", pass: "secret"}
})
module.exports = client
在你需要使用API的控制器中,像这样使用:
let client = require('client')
//let router = ...
router.get('/dashboard', (req, res) => {
// Simple GET with Promise handling to https://myapp.com/api/v1/reports/clients
client.get("reports/clients")
.then(response => {
console.log("Report for client", response.userId) // REST responses are parsed as JSON objects
res.render('clients/dashboard', {title: 'Customer Report', report: response})
})
.catch(err => {
console.error("Ups!", err)
res.status(400).render('error', {error: err})
})
})
router.get('/orders', (req, res, next) => {
// GET with query (https://myapp.com/api/v1/orders?state=open&limit=10)
client.get({"uri": "orders", "query": {"state": "open", "limit": 10}})
.then(orders => {
res.render('clients/orders', {title: 'Customer Orders', orders: orders})
})
.catch(err => someErrorHandler(req, res, next))
})
router.delete('/orders', (req, res, next) => {
// DELETE with params (https://myapp.com/api/v1/orders/1234/A987)
client.delete({
"uri": "orders/{client}/{id}",
"params": {"client": "A987", "id": 1234}
})
.then(resp => res.status(204))
.catch(err => someErrorHandler(req, res, next))
})
Reqclient支持许多特性,但是它有一些其他特性不支持的特性 库:OAuth2集成和记录器集成 使用cURL语法,并且总是返回本机Promise对象。
Unirest是我遇到的用于从Node发出HTTP请求的最好的库。它的目标是成为一个多平台框架,所以如果你需要在Ruby、PHP、Java、Python、Objective C、. net或Windows 8上使用HTTP客户端,学习它在Node上的工作方式会对你很有帮助。据我所知,unirest库大多是由现有的HTTP客户端支持的(例如,在Java上,Apache的HTTP客户端,在Node上,Mikeal的Request库)——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)
}
})
您可以直接跳转到Node文档
你也可以使用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();
}
);
尝试使用简单的http。Get (options, callback)函数在node.js:
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);
});
还有一个通用的http。请求(选项,回调)函数,允许您指定请求方法和其他请求细节。
这个版本是基于bryanmac函数最初提出的,它使用承诺,更好的错误处理,并在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();
});
};
因此,您不必传入回调函数,而是getJSON()返回一个承诺。在下面的例子中,该函数在ExpressJS路由处理程序中使用
router.get('/:id', (req, res, next) => {
rest.getJSON({
host: host,
path: `/posts/${req.params.id}`,
method: 'GET'
}).then(({ statusCode, data }) => {
res.json(data);
}, (error) => {
next(error);
});
});
当出现错误时,它将错误委托给服务器错误处理中间件。
推荐文章
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类
- 访问Handlebars.js每次循环范围之外的变量
- 如何用JavaScript截屏一个div ?
- 如何为其他域设置cookie
- 如何使用npm全局安装一个模块?
- 如何减去日期/时间在JavaScript?
- 如何检测“搜索”HTML5输入的清除?
- 字符串中的单词大写
- 返回一个正则表达式匹配()在Javascript的位置?
- Ajax成功事件不工作
- 为什么JavaScript中弃用arguments.callee.caller属性?
- 在typescript中一直使用。tsx而不是。ts有什么缺点吗?
- 实时http流到HTML5视频客户端的最佳方法
- 如何在Angular.js中配置不同的环境?