Request urlencoded body is empty in express

815 Views Asked by At

I'm trying to get url parameters in express 4.17.3 using the urlencoded middleware but the body is always empty, I reproducted it to a minimal code:

const express = require("express");

(()=>{
    const app  = express();
    app.use(express.urlencoded());
    
    app.get("/", async(req, res)=>{
        console.log(req.body); //always print '{}'
        res.send();
    });
    
    app.listen(83, ()=>{
        console.log("test app listening on port 83");
    })
})();

Here's my request

http://localhost:83/?param1=42

What am I doing wrong?

1

There are 1 best solutions below

1
On

A few things to break down. To answer your question to get params you can use req.query so your code would be:

app.get('/', async (req, res) => {
  console.log(req.query)
  res.send()
})

Addressing urlencoded it should be changed from:

app.use(express.urlencoded());

to:

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

good habit to not hard code the port so the line of code:

app.listen(83, ()=>{
  console.log("test app listening on port 83");
})

should be:

const PORT = process.env.PORT || 83

app.listen(PORT, () => {
  console.log(`test app listening on port ${PORT}`)
})

full working code example:

const express = require('express')
const app = express()

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

const PORT = process.env.PORT || 83

app.get('/', async (req, res) => {
  console.log(req.query)
  res.send()
})

app.listen(PORT, () => {
  console.log(`test app listening on port ${PORT}`)
})

When using express I also like to implement nodemon and if you add this to your package.json:

"dev": "nodemon node index.js"

then in the terminal you can run:

npm run dev

you wont have to restart your server during development changes.