Lovika
Lovika

Reputation: 617

Write a route ('/form') that processes HTML form input

I am attending a workshop for nodejs and expressjs on nodeschool.io and came across this exercise but when I try out the solution it is not working.

I don't see any route being created for form.

The solution I found is:

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

var bodyparser = require('body-parser');


app.use(bodyparser.urlencoded({extended: false}));

app.post('/form',function(req,res){
    //res.sendFile(path.join(__dirname + '/public/index.html'));
    res.send(req.body.str.split(" ").reverse().join(" "));
});

app.listen(Number(process.argv[2]));

Could anyone help me and tell me what is wrong with the solution provided?

Upvotes: 0

Views: 43

Answers (2)

HexaCrop
HexaCrop

Reputation: 4293

use an app.get request before the app.post request to get the form.

so it is like;

app.get('/form',function(){});

and then

app.post('/form',function(){});

Upvotes: 1

cassini
cassini

Reputation: 365

From the code you've provided, the route will be called on POST HTTP request. So that will be called after you submit your form and it is not responsible for any HTML rendering (if we leave the endpoint this way).

However, you can see there is a commented line, which would be the HTML rendering (perhaps the index.html file contains the form?). To get that work, you can make a new route

app.get('/form', ...)

which will return the HTML file and the form.

Upvotes: 0

Related Questions