直接上代码:
import
*
as
http
from
"http"
import
*
as
https
from
"https"
// 发送手机短信验证码接口
// 由于是异步发送,增加回调函数获取结果
function
onSentSms
(
mobile
:
string
,
callback
:(
success
:
boolean
)
=>
void
){
let
qs =
require(
'querystring');
let
sign =
'';
// 发送短信签名
let
postData = {
app_id:'10000',
sign_type:
'MD5',
type:
10,
mobile:mobile,
version:
"1.3"};
//这是需要提交的数据
let
content =
qs.
stringify(
postData);
let
options = {
hostname:
'www.baidu.com',
port:
443,
path:
'/index.php',
method:
'POST',
headers: {
'Content-Type'
:
'application/x-www-form-urlencoded; charset=UTF-8',
'Content-Length'
:
content.
length
}
};
let
result =
https.
request(
options,
function(
request){
if (
request.
statusCode ==
200){
let
resultData =
'';
request.
setEncoding(
'utf8');
request.
on(
'data', (
chunk)
=> {
resultData +=
chunk;
});
request.
on(
'end', ()
=> {
console.
log(
'result: ' +
resultData);
let
parsedData =
JSON.
parse(
resultData);
if ( !
parsedData.
success){
callback(
false); // 调用回调函数
}
else{
callback(
true); // 调用回调函数
}
})
}
else{
console.
log(
'status code: ' +
request.
statusCode);
console.
log(
'HEADERS: ' +
JSON.
stringify(
request.
headers));
}
});
result.
on(
'error',
function(
e) {
console.
log(
'请求出错: ' +
e.
message);
});
result.
write(
content);
// 发送内容
result.
end();
}
// 调用
onSentSms
(
'13800138000'
,
function
(
success
:
boolean
){
if(
success){
console.
log(
'success is true');
}
else{
console.
log(
'success is false');
}
});