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