2016-04-11 17 views
0

gibi bir istekte bulunun. HTTP kodumda, kullanıcı isteğine yanıt vermek için http modülünü kullanıyorum. JSON beklediğim request gövdesini almak istiyorum.nodejs - php's file_get_contents

var http = require("http") 
var server = http.createServer(function(request, response) { 

    console.log("method: " + request.method) 
    console.log("url: " + request.url) 
    console.log("headers: " + request.headers) 

    var body = [] 

    request.on("error", function(error) { 

     console.log("Incoming request error: " + error) 

    }).on("data", function(chunk) { 

     body.push(chunk) 

    }).on("end", function() { 

     var content = Buffer.concat(body).toString 

     console.log("request body: " + content) 
     response.end("IP: " + request.connection.remoteAddress + "<br>" + content) 

    }) 

}).listen(PORT, function() { 
    console.log((new Date()) + " Server is listening on port " + PORT) 
}) 

Ben Terminalinde komutu aşağıdaki ile yukarıdaki kodu test etmeye çalıştı: this link den değinen

, ben aşağıdaki gibi benim kod için geçerli

curl -d '{"MyKey":"My Value"}' -H "Content-Type: application/json" http://myserverdomain.com:PORT 

Ama yanıtı ben ne değildir bekliyoruz ({"MyKey":"My Value"})! Bunun yerine, nereden geldiğini bilmediğim bir kod pasajıdır. Aşağıya bakınız:

IP: <MY_IP_ADDRESS><br>function (encoding, start, end) { 
    encoding = String(encoding || 'utf8').toLowerCase(); 

    if (typeof start !== 'number' || start < 0) { 
    start = 0; 
    } else if (start > this.length) { 
    start = this.length; 
    } 

    if (typeof end !== 'number' || end > this.length) { 
    end = this.length; 
    } else if (end < 0) { 
    end = 0; 
    } 

    start = start + this.offset; 
    end = end + this.offset; 

    switch (encoding) { 
    case 'hex': 
     return this.parent.hexSlice(start, end); 

    case 'utf8': 
    case 'utf-8': 
     return this.parent.utf8Slice(start, end); 

    case 'ascii': 
     return this.parent.asciiSlice(start, end); 

    case 'binary': 
     return this.parent.binarySlice(start, end); 

    case 'base64': 
     return this.parent.base64Slice(start, end); 

    case 'ucs2': 
    case 'ucs-2': 
    case 'utf16le': 
    case 'utf-16le': 
     return this.parent.ucs2Slice(start, end); 

    default: 
     throw new TypeError('Unknown encoding: ' + encoding); 
    } 
} 

Sorunu kodumda gösterebilir misiniz? Yukarıdaki kod snippet'i neden {"MyKey":"My Value"} yerine geri döndü?

Çok teşekkürler.

Edit1: Sadece Terminal'de daha detaylı komutu, ama yine de başarısız çalıştı

.

curl -H "Content-Type: application/json" -X POST -d '{"My key":"My value"}' http://myserverdomain.com:PORT 

cevap

0

Sadece şu an problemi çözüyorum: var content = Buffer.concat(body).toString! var content = Buffer.concat(body).toString() olmalı! En önemli kısmını kaçırdım ().

Teşekkürler, herkes