亲宝软件园·资讯

展开

node.js传参给PHP失败,headers加上'Content-Length': Buffer.byteLength(content)

HIIT 人气:2

node.js需要传参给PHP,执行计划任务

var events = require('events'); 

start_cron("gc","www.y.com",80,"/cron.php",30000,{"auth":"7wElqW6vG2FcjnhomEckLg1W2t6uP5ZE0VlwjRrinrFmS3MODuvVFvhAGWeCwNRp"}); 

function start_cron(name,host,port,url,timespan,postdata)
{    
    var emitter = new events.EventEmitter(); 
    var cronInterval = null;
    
    emitter.on(name, function() {     
        clearInterval(cronInterval);
        var http = require('http');
        var qs = require('querystring');  
        var content = qs.stringify(postdata); 
        
        var options = {
            hostname: host,
            data:postdata,
            port: port,
            path: url,
            method: 'POST',
            headers: {  
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        };
        var req = http.request(options, function (res) {
            cronInterval = setInterval(function() { 
                    emitter.emit(name); 
            }, timespan);
            //console.log('STATUS: ' + res.statusCode);
            //console.log('HEADERS: ' + JSON.stringify(res.headers));
            res.setEncoding('utf8');
            res.on('data', function (chunk) {                
                console.log('BODY: ' + chunk);
            });
        });
        req.on('error', function (e) {
            cronInterval = setInterval(function() { 
                emitter.emit(name); 
            }, timespan);
            console.log('problem with request: ' + e.message);
        });
        
        req.write(content); 
        req.end();        
    });
    
    cronInterval = setInterval(function() { 
        emitter.emit(name); 
    }, timespan);

}

PHP接收不到auth值。。

$auth = trim($_POST['auth']);

解决方案在headers中加入'Content-Length': Buffer.byteLength(content)

解释:Buffer.byteLength(字符串,编码方式)计算指定字符串的字节数

Buffer.byteLength(string[, encoding])

  • string {String} | {Buffer} | {TypedArray} | {DataView} | {ArrayBuffer}
  • encoding {String} 默认:'utf8'
  • 返回:{Number}

当 string 是一个 Buffer / DataView / TypedArray / ArrayBuffer 时,返回实际的字节长度。

除此之外,将转换为 String 并返回字符串的字节长度。

有时候不加这个会没法解析数据

headers: {  
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',  
                'Content-Length': Buffer.byteLength(content)
            }

 

加载全部内容

相关教程
猜你喜欢
用户评论