I am using get Method and trying to send data to my nodejs
server using a jQuery ajax call.
Here is my code of send data to the node
:
$(document).ready(function() {
usid();
function usid(med) {
console.log("I am In");
var f = "my new name";
$.ajax({
crossDomain: true,
url:"http://localhost:8080/listUsers",
method:"GET",
data: { med: med, f: f },
success : function(data, status) {
console.log("send");
}
})
}
})
And in my node js sever I am trying to get this data with this code:
var express = require('express');
var bodyParser = require('body-parser');
const path = require("path");
var cons = require('consolidate');
var cors = require('cors');
const jsdom = require('jsdom')
const dom = new jsdom.JSDOM("")
const params = require('params');
const jquery = require('jquery')(dom.window)
var app = express();
app.use(cors())
app.engine('html', cons.swig)
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.static(path.join(__dirname, "www")));
app.get('/listUsers', function (req, res) {
res.render('try');
var f = (req.body.f);
console.log("hello" + f);
})
var server = app.listen(8080, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
But in my console I get an "undefined" error.
Can you tell me what am I missing here?
GET requests do not have a body (req.body). You could change the request to a POST and then you will have a body or you can use the queryString. Here is an example https://nodejs.org/en/knowledge/HTTP/clients/how-to-access-query-string-parameters/
$.ajax({
crossDomain: true,
url:"http://localhost:8080/listUsers?med=" + med + "&f=" + f,
method:"GET",
success:function(data,status){
console.log("send");
}
})
Then on the server
app.get('/listUsers', function (req, res) {
var f = (req.query.f);
console.log("hello" + f);
})