#Sending FormData to express backend isnt working

37 messages · Page 1 of 1 (latest)

copper perch
#

I have a form with inputs and a submit button. the inputs all have the name attribute. my event listener does work on form submit. however, i cant seem to get the data of the form in order to send it through a fetch

#
FRONTEND: 

async function uploadForm(form) {
    const data = new FormData(form);
    
    const response = await fetch("/register", {
        method: "POST",
        body: JSON.stringify(data)
    });

    return response.json();
}

RegisterForm.addEventListener("submit", async (event) => {
    event.preventDefault();
    
    const data = await uploadForm(RegisterForm);
}


BACKEND:
app.post("/register", (req, res) => {
    console.log(req.body.username) // -> undefined
    res.json("Received")
});
desert salmon
#

are you sure you are sending a body value with the name "username"?

#

it looks like you are just sending some data to the backend

copper perch
#

the form data

desert salmon
#

but are you calling it correctly

#

?

copper perch
#

which has an input with the name "username"

#

what do you mean

desert salmon
#

instead of

mossy gulch
#

you don't need to stringify formdata

copper perch
#

true anyways still get undefined

mossy gulch
#

did you set up the body parser on your server?

copper perch
#

yes

#
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
``` these are the two lines i used
desert salmon
#
body: JSON.stringify(data)

try

body: {
  username: "yourdata" 
}
mossy gulch
#

well it should show an empty object instead of undefined 🤔

#

oh wait you logged .username nvm

copper perch
#

its undefined because im trying to access the property

#

yea

desert salmon
#

try my fix above

copper perch
#

it is empty though if i just do "req.body"

#

@desert salmon ive done that before it does work

#

its something wrong with my form data

desert salmon
#

yeah

#

but i learned you should always specify and transfer data that way

#

so you know where the problem lies

mossy gulch
#

you either use formdata or stringify a js object

#

passing an object doesn't work

copper perch
#

i just want the form data

mossy gulch
#

what does your form look like?

#

do the inputs have names?

copper perch
#

<form enctype="multipart/form-data" action="/register" method="POST" id="registerForm"></form>

#

yes

#
<input
  autocomplete="off"
  name="email"
  placeholder="Email Address"
  type="email"
  class="form-control"
/>
``` this is an example of one of the three
mossy gulch
#

did you solve this @copper perch? no solution but curious what the issue was

#

sounds like the backend is working correct, if the form contains an input with a name username, I would expect body: new FormData(form) to work