Home > other >  Why i can not retrieve data from req.body
Why i can not retrieve data from req.body

Time:07-03

What i want to do is to read the property name of the request i send to my express.js server.Here is how i pass the json data to a post request.

document.querySelector('#checkout').onsubmit= async e =>{
    const form = new FormData(document.querySelector('#checkout'))
    let user = createUserInfo(form),
    

    order = {
       name: "Test_Name"
    }

    fetch("/checkout/create-order", {
        method: "POST",
        mode: "same-origin",
        redirect: 'manual',
        headers:{
            "Content-Type": "application/json"
        },
        body: JSON.stringify(
            {
                order: order,
                user: {
                   name:"test_Name"
                }

            }
        )
    }).then(res=>{
       res.ok
    }).then(data=>{
        console.log(data)
    })
}

And this is how i read it using express.js:

app.use(express.json());
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: false }));
const YOUR_DOMAIN = 'http://localhost:4242/checkout.html';

app.post('/checkout/create-order', async (req, res) => {
  console.log(req.body.order.name)
}

When i try to read the name property i get an error.

C:\xampp\htdocs\server.js:9
  console.log(req.body.order.name)
                             ^

TypeError: Cannot read properties of undefined (reading 'name')

CodePudding user response:

Add e.preventDefault() to the beginning of the onsubmit handler.

By default, when the user clicks a form submit button, the browser will send a URL encoded POST request to the URL defined in the form's action attribute (or if there is no action, the current page).

<form action="/somewhere_else"></form>

Your express code is seeing the request sent from the browser, which doesn't have any of the values you defined in the fetch request.

This also causes the page to reload and interrupt your fetch request code before its sent. By adding event.preventDefault() you suppress this behavior and your code should run as expected.

P.S. You don't need to use both express.json() and bodyparser.json(). Body-parser is included with Express, so both of those middlewares are doing the same thing. You can also use express.urlencoded() instead of bodyparser.urlencoded().

  • Related