0

I am trying to pass amount from ajax to node js, but all I am getting is undefined in the node server. Here is the ajax code.

self.information = function() {
    var x = {"amount" : self.amount()};
    var string = JSON.stringify(x);
    console.log(string);
      $.ajax({
          type: 'GET',
          url: 'http://localhost:3000/getIOT',
          contentType: 'application/json; charset=utf-8',
          dataType: 'json',
          data: string
      })
      .done(function(result) {
       console.log(result);
      })
      .fail(function(xhr, status, error) {
          console.log(error);
      })
      .always(function(data){
      });
  }
}

The console.log(string) shows {"amount" : "1000"} which looks right to me. And now in the node js server I am trying to see the variable name, but it shows undefined.

const path = require('path');
const http = require('http');
const express = require('express');
const cors = require('cors');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var requestify = require('requestify');
var request = require('request');
var helmet = require('helmet');
var https = require('https');

var app = express();
app.use(helmet());

const publicPath = path.join(__dirname, '../public');
const port = process.env.PORT || 3000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(express.static(publicPath));


app.get('/getIOT', function (req, res , err) {
            console.log('body: ' + JSON.stringify(req.body));
             // SHOWS {}  above
            var amount = req.body.amount;
            console.log(req.body.amount);
            // SHOWS UNDEFINED ABOVE 
});



app.listen(port, () => {
  console.log(`Server is up on ${port}`);
});

Using knockout js for amount, hence self.amount()

2 Answers 2

2

If you want to use get, just send the data as query string by changing the content-type to application/x-www-form-urlencoded and send as json object

if you want to post:

 amount=12&otherprop=xxx

Change to

 var x = {"amount" : self.amount()};
 $.ajax({
      type: 'GET',
      url: 'http://localhost:3000/getIOT',
      contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
      dataType: 'json',
      data: x
  });

In nodejs

Use req.query to get the data back

app.get('/getIOT', function (req, res , err) {
            console.log('body: ' + req.query);
             // SHOWS {}  above
            var amount = req.query.amount;
            console.log(req.query.amount);
            // SHOWS UNDEFINED ABOVE 
});
Sign up to request clarification or add additional context in comments.

6 Comments

Your answer helped me perfectly, but I want to ask, the POST did not work for me, can you tell me why it caused me an error?
I Get a error. SyntaxError: Unexpected token a at parse (/Users/nihit/Documents/node/multiple-js/node_modules/body-p‌​arser/lib/types/json‌​.js:83:15) at /Users/nihit/Documents/node/multiple-js/node_modules/body-pa‌​rser/lib/read.js:116‌​:18 at invokeCallback (/Users/nihit/Documents/node/multiple-js/node_modules/raw-bo‌​dy/index.js:262:16) at done (/Users/nihit/Documents/node/multiple-js/node_modules/raw-bo‌​dy/index.js:251:7)
Oh.. Just parse the json string instead of stringify. Change JSON.stringify(req.body) to JSON.parse(req.body);
You're sending json string to nodejs, why you have to stringify that again. Just parse that json string if you want to use post.
Also remove bodyParser.urlencoded({extended:false}). This tell the browser to send url form encoded data rather than json.
|
1

I believe that jQuery's .ajax sends the data in query parameters if you use an HTTP GET request. I'd check req.query rather than req.body, or change the ajax call be type: 'POST' to get it in req.body.

If that just sounds like a bunch of nonsense, I can try to explain in more detail :)

15 Comments

Since OP set the contentType to contentType: 'application/json' in the Request, it should be received in req.body
Are you sure? From the jQuery docs for the data attribute: Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
@thataustin POST gives bad request :(
I think with a POST request, you don't need to stringify it. Just pass in an JS object: data: x. Also, remember to tell the server that you're expecting a post by changin app.get to app.post. But to be honest, I think using the query params is better. Did req.query work?
@thataustin, You are on the right track (and I wasn't). GET requests do not populate req.body but POST requests do.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.