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


    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)
                }
  • 相关阅读:
    2014.5.20知识点学习:void及void指针含义的深刻解析(转载)
    2014.5.20知识点学习:void与void*(转载)
    2014.5.19知识点学习:上下文切换
    编写“全选”按钮来操作大量复选框
    排序算法(冒泡排序,选择排序,插入排序,快速排序)
    算法基础
    Git &GitHub
    flask 上下文管理 &源码剖析
    rest-framework框架的基本组件
    Django的FBV和CB
  • 原文地址:https://www.cnblogs.com/hiit/p/11918208.html
Copyright © 2020-2023  润新知