Send the contents of a front-end function via POST to Node

Asked

Viewed 693 times

0

Hello, I would like to know how to send a variable within a function via the POST method from the front end to the back end, and receive the value on the POST Express route?

In the Frond-end

function valor() {
    let valor = 10;
    //ENVIAR O VALOR UTILIZANDO POST
}

In the back end with the Express module

app.post('/valor', function(req, res) {
    //RECEBER O VALOR AQUI
});
  • 1

    Back-end: req.body.field_name or install the module(s) (s) body-parser and/or ladies (for sending files). Front-end: Use the fetch or XMLHttpRequest

1 answer

1


Luis below is a complete example where a form with a single field is posted on a given route:

Filing cabinet server.js:

const express = require('express');
const path = require('path');
const app = express();

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '/'));

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded());

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

app.post('/', (req, res) => {
    console.log('Valor postado', req.body.campo1);
    res.render('myView', { msg: 'Dados Processados' } );
});

app.listen(3000, () => console.log(`App listening on port!`));

Filing cabinet myView.ejs:

<form method="post">
    <input type="text" value="teste" name="campo1" />
    <input type="submit" value="enviar" />
</form>

I believe these links can help you:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.