1

How do I get the value of json data sent from client with ajax in node.js? I tried so many examples and q&a but still it's not working. I'm totally new to node.js so my question could be dumb. I got my codes below. Please kindly point me out where and what are wrong. I'm totally lost.

What i need is the value "TEST" from data of the json.

I tried req.body.data

Client [html]

$.ajax({
      type:"POST",
      url: 'http://localhost:8080/getFromDB',
      //data:JSON.stringify({"sql":"SELECT * FROM Track"}),
      data: '{"data": "TEST"}',
      success:function(data) {
        $('#disco').html(data);
      },
      error:function() {
        $('#disco').html('Error connecting to the server.');
      }
    });

node.js

var app   = module.exports = require('appjs');
var http  = require('http');
var url   = require('url');
var fs    = require('fs');

http.createServer(function (req, res) {

  var path = url.parse(req.url).pathname;
  var value;

  if(path == "/getFromDB") {

    // req = JSON.parse(req);
    // var testshit1 = parser(req.data);

    req.on('data', function (data) {
      value = JSON.parse(data);
    });

    // ------- e.o test -------

    res.writeHead(200, {
      'Content-Type': 'text/plain',
      'Access-Control-Allow-Origin' : '*',
      'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE'
    });
    res.end('value = ' + value);
  }

}).listen(8080);
4

3 回答 3

4

datainreq.on('data', function(data) { ... })是 a Buffer,您需要先将其转换为字符串。此外,您可以接收任意数量的data事件,这些事件需要组合在一起以构成请求正文。考虑到这些事情,步骤是:

  1. 创建一个变量来保存您的请求正文。
  2. 当您收到data有关您的对象的事件时req,请将您收到的数据附加到保存您的请求正文的变量中。
  3. 当您收到有关您的对象的end事件时,将您的请求正文转换为带有.reqJSON.parse

像这样的东西:

var body = ""; // request body

req.on('data', function(data) {
    body += data.toString(); // convert data to string and append it to request body
});

req.on('end', function() {
    value = JSON.parse(body); // request is finished receiving data, parse it
});

此外,一旦您收到整个请求正文,您很可能只想使用 , 等进行响应res.writeHead,因此请在请求的事件处理程序中执行此操作:res.endend

req.on('end', function() {
    value = JSON.parse(body); // request is finished receiving data, parse it

    res.writeHead(200, {
      'Content-Type': 'text/plain',
      'Access-Control-Allow-Origin' : '*',
      'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE'
    });
    res.end('value = ' + value);
});
于 2014-09-17T06:42:48.280 回答
0

value的 in 节点是一个对象。用他。例子:

req.on('data', function (data) {
      value = JSON.parse(data);
      console.log("SQL is " + value.sql);
    });
于 2014-09-17T06:20:22.120 回答
0

我建议您使用本地 IP 而不是“localhost”。

您可以使用 getJSON() 然后搜索结构,或者如果您知道值在哪里,直接访问它:

$.getJSON('http://192.168.1.1:8080/getFromDB', function (data) {
         var myVar = data.features[0].TEST;
         });
于 2014-09-17T06:43:21.657 回答