nodejs实现http客户端发送请求,可通过http模块的request()方法实现。一般http消息发送可分为POST、GET、DELETE和PUT,不过此处仅以POST方式进行编写调测。本次编写有index.js和data.js脚本,其中index.js为接口模型调用方法,data.js中则将各可能会使用到的参数值以变量形式收集在一块,这样调测时我们只要对data中各参数值进行修改即可,操作性更强,使用上也更方便。
index.js:
//引入模块
var http = require('http');
var data = require('./data');
const querystring = require('querystring');
//定义请求消息头
var headers = {
'Content-type':'application/json;charset=UTF-8'
};
//定义请求消息url和头部
var options = {
method:'POST',
host:data.data.host,
port:data.data.port,
path:data.data.path,
headers:headers
};
//定义消息body
var body = {
"callerNum":data.data.callerNum,
"relationNum":data.data.relationNum,
"calleeNum":data.data.calleeNum,
"callDirection":data.data.callDirection,
"duration":data.data.duration,
"maxDuration":data.data.maxDuration
};
//发送请求
var req = http.request(options,function(res){
console.log(res.statusCode);
console.log(res.header