Friday, 4 December 2020

Express, get data from POST in form and INSERT into DB

 HTML file contains the following form:

<form action="/insertHolding" method="POST">

    <label for="hodl">Hodl</label><br>

    <input type="text" id="hodl" name="hodl"><br>

    <input type="submit" value="Submit">

</form>

In order to get the POST action from clicking the Submit button of the form, you must have the following

code in the app.js file:

app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.post('/insertHolding', function (req,res) {     db.query("INSERT INTO posessions (coin,amount) VALUES ('BTC',?)",[req.body.hodl], function (err,result) {

There is no body property on a standard Node.JS HTTP request. That key is patched on by the

 bodyParser middleware. We must add the bodyParser middleware.

https://stackoverflow.com/questions/44554038/typeerror-cannot-read-property-of-undefined-expressjs-post We have also installed express module by connecting to the running node container (docker exec -ti node bash). npm install express --save insert also the dependency into package.json