At the moment, I'm taking the web development course with Node.js.
The question is: I have a simple HTML form where a user can enter the first and the last name. The route for this operation is /name.
I have a handler for GET requests where the first and the last names are passed in the URL parameters. Also, I have a handler for POST requests where I can fetch the full name from the request body.
Here is my index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Hello HTML</title>
<link rel="stylesheet" href="/public/style.css">
</head>
<body>
<h1>Hello, HTML.</h1>
<p>Do not use until Challenge #12</p>
<form action="/name" method="post">
<label>First Name :</label>
<input type="text" name="first" value="John"><br>
<label>Last Name :</label>
<input type="text" name="last" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Full myApp.js file:
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
// app.get("/", function(req, res) {
// res.send('Hello Express');
// });
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', (req, res, next) => {
console.log(req.method + " " + req.path + " - " + req.ip);
next();
});
app.use('/public', express.static(__dirname + "/public"));
app.get('/:word/echo', (req, res) => {
res.json({echo: req.params.word});
});
app.get('/', (req, res) => {
res.sendFile(__dirname + "/views/index.html");
});
app.get('/now', (req, res, next) => {
req.time = new Date().toString();
next();
}, (req, res) => {
res.json({time: req.time});
});
app.get('/json', (req, res) => {
if (process.env.MESSAGE_STYLE === "uppercase") {
res.json({"message": "HELLO JSON"});
} else {
res.json({"message": "Hello json"});
}
});
app.route('/name')
.get((req, res) => {
res.json({name: req.query.first + " " + req.query.last});
})
.post((req, res) => {
let string = req.body.first + " " + req.body.last;
res.json({name: string});
});
When I submit form data, I'm receiving this JSON response: {name: "undefined undefined"}
But all the test are passed. Nonetheless, why the app behaves this way?