Home > Enterprise >  Express routes not rendering
Express routes not rendering

Time:03-17

I can't figure out why my route 'scrape will not render. I have tried everything I can think of, even changing everything to a very basic route and I just cannot get anything to work.

app.js

const indexRoute = require("./routes/index");
const scrapeRoute = require("./routes/scrape");

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

app.use(logger("dev"));

// Routes
app.use("/", indexRoute);
app.use("/scrape", scrapeRoute);

module.exports = app;

here is the route:

const express = require("express");
const router = express.Router();

router.post("/", (req, res) => {
    res.send(req.body);
});

module.exports = router;

the index route works just fine. for some reason the route 'scrape' just will not work. I had logic in there to scrape a website but when that wasn't working I figured I'd change it to just a basic route to see if I'm even getting anything and now it's just sending a 404 when I go to localhost:9000/scrape

CodePudding user response:

If you're just going to http://localhost:9000/scrape in the browser, then that is a GET request, not a POST request. And, you would need:

const express = require("express");
const router = express.Router();

router.get("/", (req, res) => {
    res.send("hello");
});

module.exports = router;

To get a response from that - change to router.get(). And, because it's a GET request, there is no body so req.body would predictably be empty for a GET request.


To send a POST request from a browser, you either need have the browser submit a form with method="POST" and action="/scrape" as a attributes of the <form> tag or you need to use Ajax to programmatically send a POST request from Javascript using the fetch() interface or the XMLHttpRequest interface.

CodePudding user response:

Are you sure you are making a post call from the client?

  • Related