I am using node js package express js to store user input data and return username stored after user click submit button.
Server Error (http://localhost:3000/store-user): TypeError: Cannot read property 'username' of undefined
For app.js file :
const express = require('express');
const app = express();
//Change it to javascript object
app.use(express.urlencoded({extended: false}));
//Get request that send by browser
app.get('/currentime', function(req,res) {
res.send('<h1>' new Date().toISOString() '</h1>');
}); //localhost:3000/currenttime
app.get('/',function(req,res){
res.send('<form action="/store-user" method="POST"><label>Your Name</label><input type="text" name="username"><button>Submit</button></form>');
})//localhost:3000/
app.post('/store-user', function(res,req) {
const userName = req.body.username;
console.log(userName);
res.send('<h1>Username stored!</h1>');
});
app.listen(3000)
CodePudding user response:
req.body?.username
This code save your error but not a good solution.
app.post('/store-user', function(res,req) {
/* username field not set and so show error. Please check your request */
const userName = req.body.username;
console.log(userName);
res.send('<h1>Username stored!</h1>'); });