Search code examples
node.jsexpressposturlencode

urlencoded in express(node js) don't work correctly


I encountered the following problem: when submitting a form, the data from the form is not transferred,After submitting the form, there is an endless loading and no data is transferred

"express": "^4.18.2"

index.js:

import express from 'express';
import expressHandlebars from 'express-handlebars';
import hbs from 'hbs';
import bodyParser from 'body-parser';

const app = express();
const port = 3333;

const urlEncodedParser = bodyParser.urlencoded({ extended: false });
const jsonParser = bodyParser.json();

app.engine(
  'hbs',
  expressHandlebars.engine({
    layoutsDir: 'views/layouts',
    defaultLayout: 'layout',
    extname: 'hbs',
    helpers: {
      for: function (from, to, incr, block) {
        var accum = '';
        for (let i = from; i <= to; i += incr) accum += block.fn(i);
        return accum;
      },
    },
  })
);
app.set('view engine', 'hbs');
hbs.registerPartials('./views/partials');

app.get('/register', (req, res) => {
  res.render('register.hbs');
});
app.post('/register', urlEncodedParser, (req, res, next) => {
  if (!req.body) {
    res.send('hi' + req.body.userName);
  }
});

//server
app.listen(port, (err) => {
  if (err) {
    console.log('server didabled:' + err);
  } else {
    console.log('server is running on:' + port);
  }
});

HTML FORM

<form method='post'>
  <input type='text' placeholder='input name' name='userName' />
</form>

tried without body parser:

app.use(express.urlencoded({extended:false}))

app.get.....
app.post('/register',(req,res)=>{
if(!req.body)return res.sendStatus(400);
})

don't work


Solution

    1. You are using express": "^4.18.2 so you don't need to import bodyParser as it's part of express.
    2. You get an endless load because you are only returning a response on one condition, which won't work by the way.
    3. If you want to check to see if req.body is empty then you can do this:
    import express from 'express';
    //...
    // import bodyParser from 'body-parser'; //< No need for this
    
    const app = express();
    const port = 3333;
    
    //const urlEncodedParser = bodyParser.urlencoded({ extended: false }); //< No need for this
    //const jsonParser = bodyParser.json(); //< No need for this
    app.use(express.urlencoded({extended:false})); //< Add this
    app.use(express.json()); //< Add this
    //..
    
    app.post('/register', (req, res, next) => {
      if (!Object.keys(req.body).length) { //< Check for an empty req.body object
         res.send('Error: No data sent');
      }else{
         // You may want to check here for req.body.userName but that's up to you 
         res.send(`Hi ${req.body.userName}`);
      }
    });
    
    //...