Answers:
这是我的示例中的一些代码片段。它是异步的,并返回JSON对象。它可以执行任何形式的GET请求。
请注意,还有更多的最佳方法(仅作为示例)-例如,与其将放入数组的块连接起来并进行连接等,不希望将它们串联在一起。希望,它可以使您朝正确的方向开始:
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();
};
通过创建一个选项对象来调用它,例如:
const options = {
host: 'somesite.com',
port: 443,
path: '/some/path',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
并提供回调函数。
例如,在服务中,我需要上面的REST模块,然后执行此操作:
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);
});
如果您要查找async
/ await
(线性,无回调),promise,编译时支持和智能感知,我们创建了一个符合该要求的轻量级HTTP和REST客户端:
尝试在node.js中使用简单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);
});
还有一个常规http.request(options, callback)
功能,可让您指定请求方法和其他请求详细信息。
GET
如果有此URL,如何使用此请求?graph.facebook.com/debug_token? input_token={token-to-inspect} &access_token={app-token-or-admin-token}
?
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
});
您还可以使用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();
}
);
该版本基于bryanmac函数最初提出的功能,该功能使用Promise,更好的错误处理,并在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()返回一个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);
});
});
错误时,它将错误委派给服务器错误处理中间件。
get
路由定义中进行此操作,此处缺少许多文章。
Unirest是我从Node发出HTTP请求时遇到的最好的库。它的目标是成为一个多平台框架,因此,如果需要在Ruby,PHP,Java,Python,Objective C,.Net或Windows 8上使用HTTP客户端,则了解它在Node上的工作方式将为您提供良好的服务。据我所知,unirest库主要由现有的HTTP客户端支持(例如,在Java,Apache HTTP客户端,Node上,Mikeal的Request libary上)-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文档
如果您只需要发出简单的get请求并且不需要对任何其他HTTP方法的支持,请查看:simple-get:
var get = require('simple-get');
get('http://example.com', function (err, res) {
if (err) throw err;
console.log(res.statusCode); // 200
res.pipe(process.stdout); // `res` is a stream
});
使用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对象。
如果你需要发送GET
请求到IP
还有一个Domain
(其他的答案并没有提到你可以指定一个port
变量),你可以利用这个功能:
function getCode(host, port, path, queryString) {
console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")
// Construct url and query string
const requestUrl = url.parse(url.format({
protocol: 'http',
hostname: host,
pathname: path,
port: port,
query: queryString
}));
console.log("(" + host + path + ")" + "Sending GET request")
// Send request
console.log(url.format(requestUrl))
http.get(url.format(requestUrl), (resp) => {
let data = '';
// A chunk of data has been received.
resp.on('data', (chunk) => {
console.log("GET chunk: " + chunk);
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log("GET end of response: " + data);
});
}).on("error", (err) => {
console.log("GET Error: " + err);
});
}
不要错过文件顶部所需的模块:
http = require("http");
url = require('url')
还请记住,您可以使用https
模块通过安全网络进行通信。因此这两行将发生变化:
https = require("https");
...
https.get(url.format(requestUrl), (resp) => { ......
## 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)=>{
})