Как извлечь тело из запроса с экспрессом в NodeJs? - PullRequest
0 голосов
/ 03 сентября 2018

Я использую Node.Js и express framework для своего приложения.

Я создаю HTML-формы и после отправки я не могу получить свои form данные по запросу API.

Мой HTML:

<form method="post" action="/create">
    <input type="text" name="user.name" />
    <input type="text" name="user.email" />
    <input type="text" name="user.address.city" />
    <input type="text" name="user.address.land" />
    <input type="submit" value="Submit">
</form>

JSON-объект должен быть получен в моем API:

{
   "user": {
      "name": "toto",
      "email": "toto@mail.com",
      "address": {
         "city": "yyyyy",
         "land": "zzzz"
      }
   }
}

Как это сделать с Node.js, Express 4 и есть ли другая библиотека для этого?

Ответы [ 3 ]

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

Вы можете подготовить ваше собственное промежуточное программное обеспечение, которое анализирует входящие данные формы, используя urlencoded() body-parser и превращая его в структурированный JSON:

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

function setDeepValue(path, obj, value) {
  const tokens = path.split('.');
  const last = tokens.pop();
  for (const token of tokens) {
    if (!obj.hasOwnProperty(token)) {
      obj[token] = {};
    }
    obj = obj[token];
  }
  obj[last] = value;
}

app.use(bodyParser.urlencoded(), function(req, res, next) {
  let obj = {};
  for (const key in req.body) {
    setDeepValue(key, obj, req.body[key]);
  }
  req.body = obj;
  next();
});

app.post('/create', function(req, res) {
  console.log(req.body)
})
0 голосов
/ 03 сентября 2018

Следуйте этому руководству репозитория, специально созданного для руководства по обновлению nodejs-frontend-sample-for-freshers

РЕДАКТИРОВАТЬ:

Вы можете использовать Ajax для отправки формы, это также поможет в Одностраничном приложении

JS на стороне клиента:

function submit() {
    // JavaScript uses `id` to fetch value
    let email               = $("#email").val(),
        name                = $("#name").val(),
        city                = $("#city").val(),
        land                = $("#land").val();

    // Can validate each field here and show error like:
    if ( validateEmail(email) ) {
        $("#emailError").addClass("hide");
    } else {
        $("#emailError").removeClass("hide");
        return;
    }

    // form request data, doing this will get you data in correct form at NodeJs API
    let data = {
        user: {
            email,
            name,
            address: {
                city,
                land
            }
        }
    };

    $.ajax({
        "url": "/create",
        "method": "POST",
        "data": data
    })
    .then( result => {
        // On success empty all the input fields.
        $("#email").val('');
        $("#name").val('');
        $("#city").val('');
        $("#land").val('');

        // Message to notify success submition
        alert("Successfully added user.");
        return;
    })
    .catch( err => {
        // Notify in case some error occured
        alert("An error occured.");
        return;
    });
}

// Validate Email based upon pattern
function validateEmail (email) {
    if ( email && email.match(/^([A-z0-9_.]{2,})([@]{1})([A-z]{1,})([.]{1})([A-z.]{1,})*$/) ) {
        return true;
    }
    return false;
}

HTML:

<form>
    <input type="text" id="name" />
    <input type="text" id="email" />
    <span id="emailError" class="hide error">Valid Email Required</span>
    <input type="text" id="city" />
    <input type="text" id="land" />
    <p onclick="submit()">Submit</p>
</form>

Рекомендую использовать cors.js тоже как:

const cors = require('cors');

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

Вы можете получить объект двумя способами:

1: без использования дополнительных модулей, что-то вроде этого

app.post('/create', function (request, response, next) {

    let body       = [];

    request.on('error', (err) => {
        console.error(err);
    }).on('data', (chunk) => {
        body.push(chunk);
    }).on('end', () => {
        body       = Buffer.concat(body).toString();
        console.log(body); // Your object
        request.body = body;  // Store object in request again

        next();
    });
}, (req, res) => {
    console.log(req.body); // This will have your object 
});
  1. Использование body-parser с express:

`` `

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

app.post('/create', function (request, response, next) {
    console.log(request.body);  // `body-parser did what I did earlier`
});

`` `

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

В своем HTML-коде вы публикуете маршрут создания.

Так что в экспрессе вам нужно создать этот маршрут

const express = require('express')
const bodyParser = require('body-parser')
const app = express()

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

app.post('/create', function(req, res) {
  console.log('----- MY BODY -----')
  console.log(req.body)
  // do something more clever
  res.send('We posted to this route')
})

Сначала нам требуется express, затем нам требуется body-parser и, наконец, инициализировать наше express-приложение.

Затем мы используем json middlewere body-parser для синтаксического анализа тела, чтобы мы могли легко получить к нему доступ в нашем обработчике.

Затем мы определяем маршрут к '/create', который принимает запрос сообщений (помните, что ваша форма отправляет сообщения в это местоположение).

Все, что делает наш обработчик - это console.log тело запроса, а затем показывает сообщение Мы отправили на этот маршрут

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...