简体   繁体   中英

Sending AJAX POST request to Express

I have two questions. First one is, I don't know what I'm doing wrong when sending a POST request using AJAX. I am geting results back but userSrc parameter that I send is undefined.

How to send parameter so Express can read it using req.query and use it as a parameter for searching?

Here is the code:

Jquery:

$(function() {
    
    $("#userSrc").keyup( function () {
        let dInput = $("#userSrc").val();
        console.log(dInput);
      $.ajax({

        type: 'POST',
        url: '/quicksearch',
        data : {userSrc :dInput},
        
        success: function(result) {
          let html = '';
          console.log(result);
          result.each(element =>{
            console.log(element);
            html += "<h2>" + element.Title +"</h2>";
            $("#result").html(html);
          });
          
          
        }
      });
    });
  });

Express:

app.post("/quicksearch", (req, res) => {
  let search = req.query.userSrc;
  console.log(search);

  Recent.findOne({
    Title: search
  }, (err, foundData) => {
    if (err || foundData == null) {
      fetch("http://www.omdbapi.com/?s=" + search + "&apikey=b322e698")
        .then(response => response.json())
        .then(data => {
          console.log("API RESPONSE");
          console.log(data.Search);
          res.send({
            result: data.Search
          });
        });
    } else {

      
      console.log("Found Local");
      res.send( {
        result: foundData
      });
    }
  });

The second question which I have is, how to implement the result that I receive back since I've tried using Object.keys and ForEach. I am not sure how to get to the result.Title.

{result: Array(7)}
    result: Array(7)
    0: {Title: "Undefined", Year: "2006", imdbID: "tt1436480", Type: "movie", Poster: "https://m.media-amazon.com/images/M/MV5BMTgzNzkxMzk5Nl5BMl5BanBnXkFtZTgwMTQ2MzA2MDE@._V1_SX300.jpg"}
    1: {Title: "The Undefined", Year: "2013", imdbID: "tt3271334", Type: "movie", Poster: "N/A"}
    2: {Title: "Viet Costas - Citizenship: Undefined", Year: "2014", imdbID: "tt3838986", Type: "movie", Poster: "N/A"}
    3: {Title: "A Love Undefined", Year: "2015", imdbID: "tt4955578", Type: "movie", Poster: "N/A"}
    4: {Title: "Artist Undefined", Year: "2015", imdbID: "tt5190590", Type: "movie", Poster: "N/A"}
    5: {Title: "Undefined", Year: "2014", imdbID: "tt5581814", Type: "movie", Poster: "N/A"}
    6: {Title: "Undefined: A Muslim-American Musical", Year: "2017", imdbID: "tt7178924", Type: "movie", Poster: "https://m.media-amazon.com/images/M/MV5BODMwYTE1ZG…jk0ZmZhXkEyXkFqcGdeQXVyNzI4NTUyNjE@._V1_SX300.jpg"}
    length: 7
    __proto__: Array(0)
    __proto__: Object

Thanks in advance!

The express handler is getting the query parameters in the URL. Those are characters after the ? in the URL, for example, /quicksearch?search=text then req.query would be { search: "text" } .

You want to read the request body . That can be done by req.body . Make sure you add the body-parser middleware in your express app. Include the middleware:

const bodyParser = require('body-parser');
const urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(urlencodedParser); 

Now in your route handlers you have access to req.body .

Your forEach is good, but it seems you're doing it on the wrong variable. In your JavaScript, the result contains the whole body of your response. Your array is in result.result . Rewrite for your JavaScript:

$(function() {
    $("#userSrc").keyup(function() {
        let dInput = $("#userSrc").val();
        console.log(dInput);
        $.ajax({
            type: 'POST',
            url: '/quicksearch',
            data: {
                userSrc: dInput
            },
            success: function(response) { // response is the whole body
                let html = '';
                console.log(response.result);
                response.result.each(element => {
                    console.log(element);
                    html += "<h2>" + element.Title + "</h2>";
                    $("#result").html(html);
                });
            }
        });
    });
});

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