How to make a post from Express to return a Json with the variables entered in a form?

0

Hello everyone and thanks for the help!

I have the following problem and I am new to Express, it is for a work project.

What I need is to make a post from a form and that the answer is a JSON with the data entered in the form.

I'm using Express and Pug for the front-end.

My Pug form:

doctype html
html(lang='en')
 head
   title HPI
 body
   h1 Formulario HPI
  #container
   form(action="***.**.**.1*:12***/search" method="post")
   label(for='nodoHpi') Nodo Hpi
   input#nodoHpi(name='nodoHpi', type='text')
   br
   br
   label(for='nombreIndice') Nombre Indice
   input#nombreIndice(name='nombreIndice', type='text')
   br
   br
   label(for='valorIndice') Valor Indice
   input#valorIndice(name='valorIndice', type='text')
   br
   br
   button(type="submit") ENVIAR

My app.js:

const express = require('express');
const app = express();
const hostname = '***.**.**.**:12***/search';
const port = '3000';

app.set('view engine', 'pug');


app.get('/', (req, res) => {
   res.render('index');
});

app.post('***.**.**.**:12***/search', (req, res) => {
    // necesito que la respuesta de este post me devuelva un JSON con los datos ingresados en el formulario
});

app.listen(port, () => {
    console.log("The server is listening in localhost: '${port}'");
});    

This is an example of the JSON that you want to return, but there are data that are variables (which are the ones entered by the user in the form):

{
    "token": "1",
    "query": [{
        "index": "ALTC.MC_ROBERTS",
        "terms": [{
            "name": "INDEXTEXT01T",
            "value": "3044071*",
            "operator": "like"
        }],
        "results": {
            "count": 5000,
            "sort": [{
                "name": "ISSUE_DATE",
                "order": "descending"
            }],
            "fields": []
        }
    }]
}

where

** ALTC.MC_ROBERTS

INDEXTEXT01T

3044071 **

They are variable data.

    
asked by Nacho Zve De La Torre 12.09.2018 в 18:42
source

1 answer

0

You need to use body-parser on your server:

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

const port = '3000';

app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({ extended: false }))

app.get('/', (req, res) => {
  res.render('index');
});

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

  console.log(req.body.nodoHpi)
  console.log(req.body.nombreIndice)
  console.log(req.body.valorIndice)
});

app.listen(port, () => {
  console.log('The server is listening in localhost: ${port}');
});
    
answered by 14.09.2018 в 01:11