Как отправить значение поля ввода в серверную часть JS Node через AJAX-вызов для функциональности typeahead - PullRequest
0 голосов
/ 17 сентября 2018

Я пытаюсь реализовать функциональность typeahead, как показано ниже.

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

Теперь, когда я пытаюсь набрать текстовое поле «product», оно вызывает интерфейс back / search. Однако я не могу уловить значение поля продукта.

Любая помощь будет оценена? Обратите внимание, мне нужна функциональность typeahed с вызовом ajax для отправки входного текстового значения на сервер.

Вывести из трех консольных журналов следующим образом ...

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

Ответы [ 2 ]

0 голосов
/ 17 сентября 2018

express не анализирует ввод, предоставленный API самостоятельно.Таким образом, нам нужен какой-то дополнительный инструмент, такой как body-parser, для извлечения ввода из запроса и форматирования его в JSON.Это можно сделать и без body-parser.

Пройдите эту документацию , она охватывает много.

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

` ``

Без использования 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 голосов
/ 17 сентября 2018

req.body.product not req.query.product

Использование глагола IN 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));
});

Ранее я не использовал typeahead, но этот пример понятен.

...