如何通过AJAX调用将输入字段值发送到Node JS后端以进行预输入功能

时间:2018-09-17 16:06:31

标签: javascript node.js ajax typeahead.js

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

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>
...
...

我的后端 node 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 
    });

现在,每当我尝试在“产品”文本字段中键入内容时,它就会调用后端/ search api。但是,我无法获得产品领域的价值。

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

如下三个consol日志的

输出 ...

Search string >> [object Object]
Search string >> {}
Search string >> undefined

2 个答案:

答案 0 :(得分: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);
});

```

答案 1 :(得分:0)

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

在POST动词中使用body-parser Midlleware

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

我以前没有使用过提前输入功能,但是这个example很清楚。