I'm a newbie on express, and when I was creating a simple server demo I detected that POST requests were not sent. After doing some experiments I discovered that it was the express.static middleware, that somehow was interfering. I supposed it was a common error, but didn't manage to find a clue. My code is the following:
//jshint esversion:6
import express from "express";
import path from "path";
import { fileURLToPath } from "url";
import bodyParser from "body-parser";
import https from "https";
/* jshint ignore:start */
const __filename = fileURLToPath(import.meta.url);
/* jshint ignore:end */
const __dirname = path.dirname(__filename);
const app = express();
const port = 8080;
app.use(express.static(__dirname "/public"));
app.use("/", bodyParser.urlencoded({ extended: true }));
app.get("/", (req, res) => {
res.sendFile(__dirname "/index.html");
});
app.post("/", function (req, res) {
let name = req.body.name;
let email = req.body.email;
let message = req.body.message;
res.send("POST request to the homepage");
console.log(req.body);
});
app.listen(port, () => console.log(`Listening on port ${port}!`));
I'll gladly appreciate any answer or commet :)
EDIT: Apparently this error doesn't occur on Firefox, but does on Chrome and Edge
CodePudding user response:
Based on your symptoms of the POST not even being sent from the client when you added the express.static()
, I would guess that when you go to the /
route in your browser, that express.static()
was picking up an index.html
from your public
directory rather than the index.html
that you wanted from here:
app.get("/", (req, res) => {
res.sendFile(__dirname "/index.html");
});
You can fix that two ways. Either move this app.get("/", ...)
route before the express.static()
route or tell the express.static route to NOT serve index.html
like this:
// set up static file handling, but don't serve index.html for the / request
app.use(express.static(__dirname "/public", {index: false}));
CodePudding user response:
So the way express
static file serving works is that you put a /path
which you want to serve on, and the term express.static(/path/to/static/folder)
which will be published to the api.
Otherwise your entire application will be static, due to the fact that everything start with /
.
See the docs for more info.
In your case:
app.use("/your-static-endpoint", express.static(__dirname "/public"));
One more thing about your code. Stuff like static serving, error handling, body parsing are called middlewares, so if you want to apply them through the application, you shouldn't specify a path, because it might interfere with how express
handles routing.