node.js发送http(get,post)请求

直接上代码:


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');
         }
     });
                


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值