#Node JS server issue

6 messages · Page 1 of 1 (latest)

ivory tartan
#

hey im having an issue pulling info from this form in a nodejs server. i wrote this code to pull from this HTML form thru a /submit post request. But the server isint getting whats in the form values. i keep getting undefined
https://pastebin.com/eERv1q8t
thats the html
https://pastebin.com/jV1jkK0j

thats what the server looks like

calm ivy
# ivory tartan hey im having an issue pulling info from this form in a nodejs server. i wrote t...

this also happened to me...
i am not really sure what the problem in reality is but what i got from reading, is that forms do not send data as body but as fields

for that you can use npm package called
express-formidable

i think you use it like this

const express = require('express')
const formidable = require('express-formidable');

var app = express()

app.use(formidable());

app.post('/submit', async (req, res) => {
    const { cusName, phoneNumber, makeModel, serialNumber, dropoffDate, description, items } = req.fields;
    ...
});
lavish swift
#

The form is submitted through the body but using a specific format that express doesn't provide a way of parsing. Formidable handles parsing the body for you and exposes the form fields as the fields property of the request object.

#

I don't know why libraries don't provide a form parsing package since it's such a common use case. I run into the same issue with Python libraries.

fair zealot
#

Use express.urlEncoded({extended: true});.

Minimal example:

<!-- index.html -->
<form action="/route" method="post">
  <label for="email">Email:</label>
  <input type="email" name="email" id="email">
  <label for="pass">Password:</label>
  <input type="password" name="pass" id="pass">
  <button type="submit">Send!</button>
</form>
// index.js
import express from "express";

const app = express();

// This replaces bodyParser.json().
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.get("/", (req, res) => {
    res.sendFile("./index.html", {
        root: process.cwd()
    });
});

app.post("/route", (req, res) => {
    Object.entries(req.body).forEach((entry) => console.log(`Parsed ${entry[0]}: ${entry[1]}`));
});

app.listen(5000);