How do I access the variable word in my middleware sent from a JQuery AJAX call.
AJAX
....code
$.ajax({
url: "/getWords",
word: word, //value wanting to send!!!
success: function(result) {
var myJSON = result;
console.log(myJSON);
}
});
Middleware:
app.get("/getWords", function(req, res, done) {
console.log("req.body = ", req.body); //undefined ??? Looking for 'word' value
});
req.body logs undefined req.params logs {}. body parser is installed.
Thanks
UPDATE: This is my code now based on feedback:
//script.js
$.ajax({
url: "/getWords",
data: {word: "value"},
processData: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
processData: false,
success: function(result) {
var myJSON = result;
}
});
//server.js
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/getWords", function(req, res) {
console.log("value = ", req.query);
});
});
Unfortunately in the console I get - value = {} . What am I doing wrong here?
ajax()method optional parameter "settings" does not have a valid "word" option. Please, use{ data : { word : word} }to pass the variable with the request (note that it will be interpreted as a query string, switch offprocessDataflag).Sample request
Update
In addition to Nelles answer, if you want to be able to access the request body, you should use
app.post()middleware instead (assuming you want to send data via POST requests) + setmethodoption onajax()call correctly.Reference
ajax()method referencepost()method reference