javascript - req.body is undefined - nodejs - Stack Overflow

admin2025-04-21  1

Here is my html:

<form action='/new'  method='POST' >
  <span>pool name: </span>
  <input type="text" name="name" />
  <input type="hidden" name="imageSrcList" />
  <button type='submit' >Create new</button>
</form>

And here is the relevant JS:

var app = express()
app.use(fileUpload());
app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/views'));

app.post('/new', (req, res) => {
    console.log(req.body.name);
  })

The console reads out:

TypeError: Cannot read property 'name' of undefined

I have tried with console.log(req.body) and this also is undefined.

Thanks in advance!

Here is my html:

<form action='/new'  method='POST' >
  <span>pool name: </span>
  <input type="text" name="name" />
  <input type="hidden" name="imageSrcList" />
  <button type='submit' >Create new</button>
</form>

And here is the relevant JS:

var app = express()
app.use(fileUpload());
app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/views'));

app.post('/new', (req, res) => {
    console.log(req.body.name);
  })

The console reads out:

TypeError: Cannot read property 'name' of undefined

I have tried with console.log(req.body) and this also is undefined.

Thanks in advance!

Share Improve this question edited Jul 4, 2022 at 2:44 peteb 19.5k9 gold badges57 silver badges66 bronze badges asked Apr 16, 2017 at 23:40 zoecarverzoecarver 6,4832 gold badges28 silver badges56 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

You're missing the body-parser middleware which is necessary to have req.body set to a value. Express doesn't e with this by default and will need to be installed via NPM npm i --save body-parser

const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745211478a290593.html

最新回复(0)