简体   繁体   中英

Ajax call in node.js

Hi guys I am having a issue in terms of using ajax call.

I have two ajax calls so first ajax sends the data to the server and server checks and return the value and I want the returned values to the another ajax call but it seems like I am passing nothing in second ajax call.

First Ajax Call

function first(){

  $.ajax({
    url:window.location + '/first',
    type: 'post',
    data : $('form#first_form').serialize() //it will be like "name=Brad",
    success: function(response){   
      consol.log(response.name); // I checked, and it returns "Brad"

      second_ajax(response.name); //pass the returned value "Brad"

    },error: function(){

    }
  });
}

Second Ajax call

function second(response_name){

  $.ajax({
    url:window.location + '/second',
    type: 'get',
    data : {username:response_name}//I am not sure how to write here, I want to send like 'username=Brad'
    success: function(result){ 
    },error: function(){

    }
  });
}

Server

 app.get('/second', (req, res) => {
          //get the username from the second ajax call
          var user_name = req.body.username;} //I am getting nothing here...

req.body.username only works if you're using the body-parser middleware and the request was a POST. req.body would be the parsed body of the POST request.

If the data is in the query string (eg a query parameter) of a GET which it looks like yours is, then you want:

req.query.username

And you could incorporate that like this:

app.get('/second', (req, res) => {
      //get the username from the second ajax call
      var user_name = req.query.username;} //I am getting nothing here..
      console.log(user_name);
      res.send("got it");
});

Here's the Express doc for req.query .

And, you can see in the jQuery doc for $.ajax() that the data option puts things into the query string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM