I want to receive data from client, so I use express 4 and middleware body-parser. But I input url:localhost:5555/book, page show the message: Name: undefined, and I input url:localhost:5555/book/form.html, page show the message Cannot POST /book/form.html. Here is my code.
form.html
<form action='./book' method='post'>
<input type='text' name='name' value='fred'>
<input type='text' name='tel' value='0926xxx572'>
<input type='submit' value='Submit'>
</form>
server.js
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.post('/book', function(req,res){
console.log(req.body.name);
console.log(req.body.tel);
res.send('Name: '+req.body.name);
res.send('country: '+req.body.tel);
res.end();
});
app.listen(5555);
From what I see, you're doing a app.post
on the route /book
so express expects a POST request.
But when you go to the url http://localhost:5555/book
you are doing a GET request, thus the error.
There should be one page (a GET request therefore a app.get
) for displaying the form and one page for accepting post requests.