2

I'm getting started with nodejs and express to build a pretty simple app.

So far I'm running a webserver and added an app.get route for my index.html that displays two forms and a submit button.

I'd like to be able to type a string in both forms, click on the submit button and than use both strings on my server (to call a function using those two strings from the forms).

server:

var express = require('express');
var app = express();

//body-parser -> not sure if thats the right approach...
var bodyParser = require('body-parser');
app.use(bodyParser.json());


 /* servers main page */
 app.get("/", function(req, res) {
    res.sendFile(__dirname + '/index.html');
 });


//POST route
app.post('/', function(req, res) {


//goal: user types string in both forms, clicks submit, values are being 
//received from server to call a function using those strings



});

 var port = process.env.PORT || 1337;
 app.listen(port, function() {
console.log("Listening on " + port);
 });

HTML:

<form action="" method="POST">
   Subject:<br>
   <input type="text" name="subject" value="default"><br>
   Message:<br>
   <input type="text" name="message" value="default"><br><br>
   <input  type="submit" name="submit" value="Submit">
</form>
alexmm
  • 99
  • 1
  • 13
  • Possible duplicate of [Send form data using ajax](https://stackoverflow.com/questions/21662836/send-form-data-using-ajax) – Stretch0 Apr 04 '18 at 09:20

1 Answers1

2

First, forget the bodyParser middleware, both json and urlencoded parsers have been included in express itself since 4.16

https://github.com/expressjs/express/releases/tag/4.16.0

Then, you don't have AJAX calls but rather a simple form, thus this is invalid

app.use(bodyParser.json());

Have

app.use(express.urlencoded({extended:true}));

Last, in your route just read POSTed values from body object attached to the request by the parsing middleware

//POST route
app.post('/', function(req, res) {

   var subject = req.body.subject;
   var message = req.body.message;

});
Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
  • Thanks, that works perfectly. I expected to need some kind of onclick-event maybe or something similar...amazing. – alexmm Apr 04 '18 at 09:48