I have an ExpressJS server setup accepting GET and POST requests to the same URL. The POST is sent by a form, and sends data to a server, however submitting the form to send data requires a page reload. To prevent this, I tried using the fetch()
function to send data, however this is resulting in an XHR Error Code 500. Submitting the form normally works just fine. Below is the code along with the problem
ExpressJS
import express from "express";
import path, { dirname } from "path";
import { fileURLToPath } from "url";
import bodyParser from "body-parser";
import { setUserData } from "./scripts/user.js";
const PORT = process.env.PORT || 3000
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const app = express();
app.set("trust proxy", true);
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, "public")))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", (req, res) => {
res.render("index");
})
app.post("/", (req, res) => {
let data = req.body;
if (data["textarea"].length != 0)
setUserData(data, req.ip);
res.redirect("/");
})
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
})
Script.js
function formSubmit(e) {
e.preventDefault();
let data = {
x: Number.parseInt(textarea.style.left),
y: Number.parseInt(textarea.style.top),
w: Number.parseInt(textarea.style.width),
h: Number.parseInt(textarea.style.height)
};
for (let key in data) {
let hiddenInput = document.createElement("input");
hiddenInput.type = "hidden";
hiddenInput.name = key;
hiddenInput.value = data[key];
form.appendChild(hiddenInput);
}
form.submit(); // This works just fine
// But this returns an error
fetch("/", {
method: "post",
body: new FormData(form)
});
}
deeptanshu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.