PHP中可以通过CUrl请求一个链接,NodeJS中可以通过Http或Https发送请求。
实现如下:
http.js
var httpServer = require("http");
var queryString = require("querystring");
class Http{
constructor(){
this.params = {};
this.isPost = false;
this.req = null;
this.hostname = '';
this.port = 80;
this.urlPath = '';
this.protocol = 'http:';
this.timeout = 10000;
this.headers = {};
}
/**
* [setParams description]
* @param {Object} [params] {key:value}
*/
setParams(params){
this.params = queryString.stringify(params);
}
setHostName(hostname){
this.hostname = hostname;
}
setUrlPath(path){
this.urlPath = path;
}
setIsPost(isPost){
this.isPost = isPost;
}
setPort(port){
this.port = port;
}
setProtocol(protocol){
this.protocol = protocol;
}
setTimeout(timeout){
this.timeout = timeout;
}
/**
* [setHeader description]
* @param {[Object]} headers [description]
*/
setHeader(headers){
this.headers = headers;
}
sendRequest(){
let options = {
protocol:this.protocol,
hostname:this.hostname,
port: this.port,
path: this.urlPath,
method: "GET",
timeout:this.timeout,
headers:this.headers
}
if (this.isPost) {
options.method = "POST";
options.headers['Content-Type'] = "application/x-www-form-urlencoded";
options.path = this.urlPath;
options.headers['Content-Length'] = Buffer.byteLength(this.params);
} else {
options.path = this.urlPath + "?" + this.params;
}
return new Promise((resolve, reject)=>{
this._request(options).then((res)=>{
this._getResponse(res).then((chunk)=>{
resolve(chunk.toString());
});
}).catch((msg)=>{
reject(msg);
});
this._requestStatus().then((err)=>{
reject(err);
});
});
}
_getResponse(res){
return new Promise((resolve, reject)=>{
//res.setEncoding('utf8');
res.on("data", (chunk) => {
resolve(chunk);
});
});
}
_requestStatus(){
return new Promise((resolve, reject)=>{
this.req.on('error', function (e) {
resolve(e);
});
if (this.isPost) {
this.req.write(this.params);
}
this.req.end();
});
}
_request(options){
return new Promise((resolve, reject)=>{
this.req = httpServer.request(options, (res)=>{
if (res) {
resolve(res);
} else {
reject("请求失败");
}
});
});
}
}
module.exports = Http;
测试以上类:
request.js
var Http = require("http.js");
class Request{
constructor(){
this.http = new Http();
}
getTest(){
this.http.setProtocol("http:");
this.http.setHostName("172.16.222.129");
this.http.setUrlPath("/test");
this.http.setParams({"key":"123","ere":"3243"});
this.http.setPort(3003);
this.http.setIsPost(0);
return new Promise((resolve, reject)=>{
this.http.sendRequest().then((res)=>{
resolve(res);
}).catch((err)=>{
reject(err);
});
});
}
}
module.exports = Request;
测试:
var Request= require("request.js");
var request = new Request();
request.getTest().then((res)=>{
console.log(res);
}).catch((err)=>{
console.log(err);
});