2017-12-06 24 views
0

node.jsサーバーに送信されたデータを読み取ろうとしています。ajaxを使用してノードjsサーバーにデータを送信する方法

クライアント側:

const sendToDB =(date)=> { 
    var xhttp = new XMLHttpRequest(); 
    var d = JSON.stringify(date); 
    xhttp.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
     console.log(d); 
    } 
    }; 
    xhttp.open("POST", "api/info", true); 
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    xhttp.send(d); 
} 

とサーバ:ノードJSサーバにxhttp.send(D)で送信されたデータを受信する方法

var http = require('http'); 
var server = http.createServer(function(req, res) { 
    res.writeHead(200, { 'Content-Type': 'text/plain' }); 
    req.on('data', function (chunk) { 
    console.log(req.body.date); 
    }); 
    res.end(); 
}); 
server.listen(3001); 

答えて

1
var server = http.createServer(function(req, res) { 
     if(req.method == "POST"){  
      var clientData = ''; 
      req.on('data', function (chunk) { 
       clientData+=chunk; 
      }); 
      req.on('end',function(){ 
       console.log(JSON.parse(clientData)); 
      }) 
     } 
     res.end(); 
}); 
でそれを期待しているよう

{ 
    date: { 
    foo: bar 
    } 
} 

: は、あなたがそのようなオブジェクトを送信してください

0

jsonデータを送信するときには、"Content-Type", "application/json"というヘッダーを使用する必要があります。お使いのサーバが身体req.body.date

関連する問題