最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - node.js - get value of json request - Stack Overflow

programmeradmin1浏览0评论

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);

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);
Share Improve this question asked Sep 17, 2014 at 6:16 NerdarNerdar 1,1132 gold badges10 silver badges23 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

data in req.on('data', function(data) { ... }) is a Buffer, you need to convert it to a string first. Also, you could receive any number of data events that need to be put together to make up the request body. With those things in mind, the steps are:

  1. Create a variable to hold your request body.
  2. When you receive a data event on your req object, append the data you receive to the variable that holds your request body.
  3. When you receive an end event on your req object, convert your request body to an object with JSON.parse.

Something like this:

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
});

Also, you'll most likely only want to respond with res.writeHead, res.end, etc once you've received the entire request body, so do that in the request's end event handler:

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);
});

Your value in node is an object. use him. Example:

req.on('data', function (data) {
      value = JSON.parse(data);
      console.log("SQL is " + value.sql);
    });

I suggest you to use Local IP instead "localhost".

You can use getJSON() and then search into structure or if you know where is the value, access it directly:

$.getJSON('http://192.168.1.1:8080/getFromDB', function (data) {
         var myVar = data.features[0].TEST;
         });
发布评论

评论列表(0)

  1. 暂无评论