Cannot POST nodejs/express

I’ve looked through a ton of posts here but haven’t found a resolution that works for me – I’m getting a "cannot POST /submit" error when using express/node.js (and heroku to host the website if that’s relevant).

Here is my index.js:

const express = require("express");
const path = require("path");
const PORT = process.env.PORT || 5000;

const app = express();

app.listen(PORT, () => console.log(`Listening on ${PORT}`));

app.use(express.static(path.join(__dirname)));

app.use(express.json());

app.use(express.urlencoded());

app.post("/submit", (req, res) => {
  // console.log(req.body);
  res.send("hi");
});

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

Here is my index.html:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <div class="container-fluid">
      <div class="row m-2">
        <div class="col">
          <div class="collapse" id="commonInputs">
            <form method="post" action="/submit" id="defaultsForm">
              <div class="form-group-row mb-3">
                <button
                  id="saveDefaultsBtn"
                  type="submit"
                  class="btn btn-primary"
                >
                  <span id="saveDefaults" class="ml-2">Save Defaults</span>
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
    <script src="../render.js"></script>
    <script
      src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
      integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
      integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/js/bootstrap.min.js"
      integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
      crossorigin="anonymous"
    ></script>
  </body>
</html>

The first get request works perfectly and everything is loaded, but when I click on the button I get the "cannot POST /submit" error

>Solution :

const express = require("express");
const path = require("path");
const PORT = process.env.PORT || 5000;

const app = express();



app.use(express.static(path.join(__dirname)));

app.use(express.json());

app.use(express.urlencoded());

app.post("/submit", (req, res) => {
  // console.log(req.body);
  res.send("hi");
});

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

app.listen(PORT, () => console.log(`Listening on ${PORT}`));

You have to listen at last line

Leave a Reply