将AJAX POST请求发送到Express

时间:2020-08-28 09:09:08

标签: javascript ajax express ejs

我有两个问题。首先是,我不知道在使用AJAX发送POST请求时我在做什么错。我正在获取结果,但是我发送的userSrc参数未定义。

如何发送参数,以便Express可以使用req.query读取参数并将其用作搜索参数?

代码如下:

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);
          });
          
          
        }
      });
    });
  });

快递:

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
      });
    }
  });

第二个问题是,自从尝试使用Object.keys和ForEach以来,如何实现收到的结果。我不确定如何获得结果。标题。

{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

谢谢!

1 个答案:

答案 0 :(得分:0)

快递服务处理程序正在URL中获取query parameters。这些是URL中?之后的字符,例如/quicksearch?search=text,则req.query将是{ search: "text" }

您想阅读request body。可以通过req.body完成。确保在快速应用中添加body-parser中间件。包括中间件:

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

现在,在路由处理程序中,您可以访问req.body

您的forEach很好,但是似乎您在错误的变量上执行了此操作。在您的JavaScript中,result包含整个响应。您的数组在result.result中。为您的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);
                });
            }
        });
    });
});