Home > OS >  Cannot POST nodejs/express
Cannot POST nodejs/express

Time:07-14

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 >
      <div >
        <div >
          <div  id="commonInputs">
            <form method="post" action="/submit" id="defaultsForm">
              <div >
                <button
                  id="saveDefaultsBtn"
                  type="submit"
                  
                >
                  <span id="saveDefaults" >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/[email protected]/dist/umd/popper.min.js"
      integrity="sha384-Q6E9RHvbIyZFJoft 2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://cdn.jsdelivr.net/npm/[email protected]/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

CodePudding user response:

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

CodePudding user response:

Maybe the app.use(express.static...) is catching all queries.

You can try to move it after the app.post

  • Related