req.body returns undefined

haya!!. So today i was thinking of trying out backend. and i installed express and nodemon and started working on it. everything seemed to be working fine until I made a form in my html and tried to receive and log data in my server.js. But it seems like req.body always returns undefined . I know the server and client side is working fine cause when I submit, it gives my the error I coded in the server.post(). That means i am indeed sending post req to my server . Here is the github code the code: https://github.com/glutonium69/Codespace_1/
GitHub
GitHub - glutonium69/Codespace_1: Testing out github codespace
Testing out github codespace. Contribute to glutonium69/Codespace_1 development by creating an account on GitHub.
25 Replies
glutonium
glutoniumOP11mo ago
my code isn't that big so i'll leave the code here as well html body
<form id="myForm" action="https://automatic-capybara-4j75wj7gjxrrh7pwr-5000.app.github.dev/submit-form" method="POST">
<label for="message">Message:</label>
<input type="text" id="message" name="message" required>
<button type="submit">Submit</button>
</form>

<script src="script.js"></script>
<form id="myForm" action="https://automatic-capybara-4j75wj7gjxrrh7pwr-5000.app.github.dev/submit-form" method="POST">
<label for="message">Message:</label>
<input type="text" id="message" name="message" required>
<button type="submit">Submit</button>
</form>

<script src="script.js"></script>
script.js
document.getElementById("myForm").addEventListener("submit", function (event) {
event.preventDefault();

const formData = new FormData(event.target);

fetch("https://automatic-capybara-4j75wj7gjxrrh7pwr-5000.app.github.dev/submit-form", {
method: "POST",
body: formData,
})
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.log(err));
});
document.getElementById("myForm").addEventListener("submit", function (event) {
event.preventDefault();

const formData = new FormData(event.target);

fetch("https://automatic-capybara-4j75wj7gjxrrh7pwr-5000.app.github.dev/submit-form", {
method: "POST",
body: formData,
})
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.log(err));
});
server.js
// server.js
import express from "express";
import cors from "cors";

const server = express();

const PORT = 5000;

// Use the cors middleware
server.use(cors());
server.use(express.json()); // Parse JSON bodies
server.use(express.urlencoded({ extended: true })); // Parse URL-encoded bodies

server.on("ready", () => {
console.log(`Server is ready`);
});

server.get("/", (req, res) => {
res.send("<h1>Server Working</h1>");
})

server.post("/submit-form", (req, res) => {
const { message } = req.body;
console.log(message);
if (message) {
res.json({ success: true, message });
} else {
res.status(400).json({ success: false, error: "Message is required" });
}
});

server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
// server.js
import express from "express";
import cors from "cors";

const server = express();

const PORT = 5000;

// Use the cors middleware
server.use(cors());
server.use(express.json()); // Parse JSON bodies
server.use(express.urlencoded({ extended: true })); // Parse URL-encoded bodies

server.on("ready", () => {
console.log(`Server is ready`);
});

server.get("/", (req, res) => {
res.send("<h1>Server Working</h1>");
})

server.post("/submit-form", (req, res) => {
const { message } = req.body;
console.log(message);
if (message) {
res.json({ success: true, message });
} else {
res.status(400).json({ success: false, error: "Message is required" });
}
});

server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
glutonium
glutoniumOP11mo ago
u can see thr error it is returning is the error from my server.js
No description
Joao
Joao11mo ago
In the network tab, how does the Request looks like? Can you console log req.body? Does it have anything at all?
glutonium
glutoniumOP11mo ago
it console.logs empty object
glutonium
glutoniumOP11mo ago
No description
Joao
Joao11mo ago
Mm I'm not sure if perhaps a specific parser for express is needed if you use formdata 😕
glutonium
glutoniumOP11mo ago
k so I found out that now u have to install body-parser separately its no longer with express so i updated my server.js
// server.js
import express from "express";
import bodyParser from 'body-parser';
import cors from "cors";

const server = express();

const PORT = 5000;

// Use the cors middleware
server.use(cors());
server.use(bodyParser.json());
server.use(
bodyParser.urlencoded({
extended: true,
}),
);
// server.js
import express from "express";
import bodyParser from 'body-parser';
import cors from "cors";

const server = express();

const PORT = 5000;

// Use the cors middleware
server.use(cors());
server.use(bodyParser.json());
server.use(
bodyParser.urlencoded({
extended: true,
}),
);
but still the same issue
Joao
Joao11mo ago
I was just reading this, maybe that's the issue... https://masteringjs.io/tutorials/express/post-form
glutonium
glutoniumOP11mo ago
lemme check
Joao
Joao11mo ago
But I find it strange that it doesn't handle FormData requests so I'm not sure if this is really necessary, even if it works.
glutonium
glutoniumOP11mo ago
it should tecnically do it cause i mean its just a post req after all
Joao
Joao11mo ago
That would be only for the routing not the parsing of data. It must send it in some format that is not plain text nor JSON. What happens if you do JSON.stringify(formData) on the client? Try with:
server.use(
bodyParser.urlencoded({
extended: true,
type: "multipart/form-data"
}),
);
server.use(
bodyParser.urlencoded({
extended: true,
type: "multipart/form-data"
}),
);
glutonium
glutoniumOP11mo ago
k so i did this this time it didnt return empty object but some sort of crypted msg xD
glutonium
glutoniumOP11mo ago
No description
glutonium
glutoniumOP11mo ago
but the req wassnt a success as it returned error to the client side ok no wait dis encryted msg it does have the form data
Joao
Joao11mo ago
Mmm well, try using that library from the link above. Maybe it really jsut doesn't handle it.
glutonium
glutoniumOP11mo ago
ok
Joao
Joao11mo ago
If you find out let me know 🤷‍♂️
glutonium
glutoniumOP11mo ago
okkii k so it turns out formidable.IncomingForm() is not a constructor not sure if they changed it or something i also searched up the pkg it seems like, it is used mostly for files
Joao
Joao11mo ago
I've definitely seen it used for regular forms, but most commonly the form object is constructed manually using the values of each input. I would personally use that, and use JSON stringify
glutonium
glutoniumOP11mo ago
gotcha tnx for the help btw
Heitor
Heitor11mo ago
I managed to get the data from the form using multer https://github.com/expressjs/multer install it with npm and add the following in your code:
const multer = require("multer")
const upload = multer()
app.post("/submit", upload.none(), (req, res) => {
... })
const multer = require("multer")
const upload = multer()
app.post("/submit", upload.none(), (req, res) => {
... })
GitHub
GitHub - expressjs/multer: Node.js middleware for handling `multipa...
Node.js middleware for handling multipart/form-data. - GitHub - expressjs/multer: Node.js middleware for handling multipart/form-data.
glutonium
glutoniumOP11mo ago
hey.. sorry for late response i did try this one and surprisingly it worked thanks you so much @Joaohey. The middleware Heitor provided seems to work just fine.. U had told me to let u know so i thought i'd do dat
Joao
Joao11mo ago
Yeah, thanks for that. It looks like it's treating it as a file somehow, but at least that's one one do get it to work
glutonium
glutoniumOP11mo ago
ya
Want results from more Discord servers?
Add your server