How to send variable to middleware using jquery ajax

1.1k Views Asked by At

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?

2

There are 2 best solutions below

2
Oleg Valter is with Ukraine On

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 off processData flag).

Sample request

$.ajax({
  url: 'myurl',
  data: {
    myVar: myVal
  },
  success: (data,status,jqXHR) => {}
});

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) + set method option on ajax() call correctly.

Reference

  1. JQuery ajax() method reference
  2. Express post() method reference
  3. GET method reference on MDN
2
Michael Nelles On

I suggest promisifying your ajax call only if you are running the ajax with nodeJS on the server side - the following works for me like a charm.

If you do not want to promisify just try the code contained within the /////

import $ from 'jquery'

export const myFunc = word => {
    return new Promise((resolve, reject) => {

      ///// don't use 3 lines before this if running ajax on client side

        var args = {
            "word": word
        }
        $.ajax({

            url: "/getWords",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            type: "POST",
            dataType : "json",
            contentType: "application/json; charset=utf-8",
            data : args,
            error: function(err) {
                reject(err)
            },
            success: function(data) {
                resolve(data)
            }
        })

    ///// don't use after this if client side

    })
})