[英]Node JS OR Express JS HTTP GET Request
我正在使用express.js,我需要调用HTTP GET请求,以获取JSON数据。请建议我一些不错的node js / express js modules / lib来执行get / post请求。
Node.js provides an extremely simple API for this functionality in the form of http.request
. Node.js以http.request
的形式为该功能提供了非常简单的API。
var http = require('http');
//The url we want is: 'www.random.com/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
var options = {
host: 'www.random.com',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}
http.request(options, callback).end();
Here I attach some more examples with POST and custom headers. 在这里,我附加了一些带有POST和自定义标头的示例。 If you don't need special things, I'd stick to the native code. 如果您不需要特殊的东西,我会坚持使用本机代码。
Besides, Request , Superagent or Requestify are pretty good libraries to use. 此外, Request , Superagent或Requestify是非常好的库。
var express = require('express');
var app = express();
var fs = require('fs');
app.get('/', function (req, res) {
fs.readFile('./test.json', 'utf8', function (err, data) {
if (err) {
res.send({error: err});
}
res.send(data);
})
});
var server = app.listen(3001, function () {
console.log('Example app listening port 3001');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.