如何通过AJAX调用将输入字段值发送到Node JS后端以获得typeahead功能

问题描述 投票:0回答:2

我正在尝试实现如下的预先输入功能。

HTML页面

...
...
    <input id="product" name="product" type="text" class="form-control" placeholder="Enter Product Name" autocomplete="off">
...
...  
    <script>
                $(document).ready(function () {
                    fetchTypeAheadResult();
                });

                function fetchTypeAheadResult() {
                    $('#product').typeahead({
                        source: function (request, response) {
                          var formData = {
                            'product' : $('#product').val()
                          }
                          // var formData = $('form').serialize();
                          $.ajax({
                                url: "/search",
                                dataType: "json",
                                type: "POST",
                                data: formData,
                                contentType: "application/json; charset=utf-8",
                                success: function (result) {
                                    var items = [];
                                    response($.map(result, function (item) {                            
                                        items.push(item.name);
                                    }))
                                    response(items);

                                    // SET THE WIDTH AND HEIGHT OF UI AS "auto" ALONG WITH FONT.
                                    // YOU CAN CUSTOMIZE ITS PROPERTIES.
                                    $(".dropdown-menu").css("width", "100%");
                                    $(".dropdown-menu").css("height", "auto");
                                    $(".dropdown-menu").css("font", "12px Verdana");
                                },
                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                    alert(textStatus);
                                }
                            });
                        },
                        hint: true,             // SHOW HINT (DEFAULT IS "true").
                        highlight: true,        // HIGHLIGHT (SET <strong> or <b> BOLD). DEFAULT IS "true".
                        minLength: 1            // MINIMUM 1 CHARACTER TO START WITH.
                    });
                }
            </script>
...
...

我的后端节点js代码如下

    'use strict';
    const express = require('express');
    const bodyParser = require('body-parser');
    const request = require('request');
    const app = express();

    // configure the app to use bodyParser() to extract body from request.
    app.use(bodyParser.urlencoded({ extended: true }));
    // parse various different custom JSON types as JSON
    app.use(bodyParser.json({ type: 'application/*+json' }));

     app.post('/search', (req, res) => {
      let searchText = req.body;

    console.log('Search string >> ' + req);
    console.log('Search string >> ' + JSON.stringify(req.body));
    console.log('Search string >> ' + req.body.product);

// Not correct, but still trying if it works
      // var result = triestrct.get(req.body.product);
      res.send({test:'text'});    // TODO - to be updated with correct json 
    });

现在,每当我尝试在“产品”文本字段上键入时,它都会调用后端/搜索API。但是,我无法捕获产品领域的价值。

任何帮助将不胜感激 ?注意,我需要使用ajax调用的typeahead功能将输入文本值发送到后端。

三个控制日志的输出如下......

Search string >> [object Object]
Search string >> {}
Search string >> undefined
javascript node.js ajax typeahead.js
2个回答
1
投票

express不解析自己提供给API的输入。因此,我们需要一些额外的工具,如body-parser来获取请求的输入并将其格式化为JSON。这可以在没有body-parser的情况下完成。

要经历这个documentation,它涵盖了很多。

  1. 使用body-parser,您需要使用body-parser设置express

```

const bodyParser                  = require('body-parser'),
// For Cross-Origin Resource Sharing
      CORS                        = require('cors'),
        express                     = require('express');

  const app                         = express();

  // Cross-Origin Resource Sharing
  app.use(CORS());

  // configure the app to use bodyParser() to extract body from request.
  // parse urlencoded types to JSON
  app.use(bodyParser.urlencoded({
  extended: true
  }));

  // parse various different custom JSON types as JSON
  app.use(bodyParser.json({ type: 'application/*+json' }));

  // parse some custom thing into a Buffer
  app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }));

  // parse an HTML body into a string
  app.use(bodyParser.text({ type: 'text/html' }));


  // This will get you input at `req.body`

 app.post('/search',(req,res)=>{
     console.log(JSON.stringify(req.body));
 });

```

  1. 不使用body-parser

```

app.post('/', (req, res, next) => {

    let body = [];

    req.on('error', (err) => {
        console.error(err);
    }).on('data', (chunk) => {
        // Without parsing data it's present in chunks.
        body.push(chunk);
    }).on('end', () => {
        // Finally converting data into readable form
        body = Buffer.concat(body).toString();

        console.log(body);

        // Setting input back into request, just same what body-parser do.
        req.body = body;
        next();
    });

}, (req, res) => {
    console.log(req.body);
});

```


0
投票

req.body.product不是req.query.product

在POST动词中使用qazxsw pi中间件

body-parser

我以前没有使用过类型,但这个const bodyParser = requier('body-parser'); const express = require('express'); const app = new express(); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json()) app.post('/search',(req,res)=>{ console.log(JSON.stringify(req.body)); }); 很清楚。

© www.soinside.com 2019 - 2024. All rights reserved.