I want to make a post request with this HTML code:
<!DOCTYPE html>
<form action="/post-test" method="post">
<input type="text" id="name" />
<input type="submit" value="submit">
</form>
And then write on the backend console the request. So here is my backend code:
const path = require('path');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(express.static(path.join(__dirname, 'views')));
app.use(bodyParser.json());
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, "/views/html/test.html"));
});
app.post('/post-test', async function(req, res) {
const data = req.body;
console.log(data.name);
});
When I type something in the input and press submit, the console say undefined. Where is the problem and have you the solution ?
CodePudding user response:
in the form add the name parameter and put a value, that is insert in the body of the request
<form action="post-test" method="post">
<input type="text" id="name" name="name"/>
<input type="submit" value="submit">
</form>
in the backend you access with
req.body.name
CodePudding user response:
change form action to route name
<form action="/createGazme" method="post">
</form>
CodePudding user response:
You have multiple problems.
Typo in the path
action="/post-test"
and app.post('/createGazme'
need to match
Form controls post name=value data
Your input doesn't have a name
so it won't post any data. Give it one.
<input type="text" name="name">
The id
attribute is used for client-side purposes such as being a link target or associating a <label>
using a for
attribute.
Your body parser is for the wrong data type
Forms, by default, post data in application/x-www-form-urlencoded
. You can use the enctype
attribute to change that to multipart/form-data
.
Your body parser — app.use(bodyParser.json());
can only process application/json
bodies. You need a body parser that supports the data format you are actually using.
The body-parser
module is obsolete anyway. Express has a built-in one.
express.json()
will do what your current module does (and still not work).
express.urlencoded()
will support your form.
app.use(bodyParser.urlencoded());