I have set up my code in server.js which worked fine. I am now trying to clean up the server.js code by splitting the code into different routes.
I am using the express.Router to link up the files but i am struggling to understand why my post route is braking.
In the server.js file
// dependencies
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyparser.urlencoded({extended: true}));
app.set('view engine', 'ejs');
// routes
constpurchaseOrders = require("./routes/purchaseOrders");
app.use("/purchaseOrders", purchaseOrders);
// listen
app.listen(3000, function(){
console.log("Server started on port 3000");
});
In the purchaseOrders.js file
// dependencies
const express = require("express");
let router = express.Router();
const mongoose = require("Mongoose");
const connection = require("../routes/mongoose.js");
const Po = require("../routes/schemas.js:);
// post route
router.post("/addpo, function(req.res){
//long code lines here
po.save();
res.redirect("/");
});
module.exports = router;
So with this route, i have the following end point on the route.get:
10.0.0.15:3000/purchaseOrders/addpo
Now the problem comes in when i submit the form, it returns "cannot POST /addpo" and the end point shows:
10.0.0.15:3000/addpo
On my ejs file i have set the form up as follows:
<form action="/addpo" method="post">
On the mongoose.js connection i export as follows:
module.exports = mongoose;
On the schemas.js i export:
module.exports = Po;
I know I did something wrong with the routing but i cannot figure our why.
Thanks alot :-)
CodePudding user response:
if you need the /addpo
path to work, change this on server.js
:
app.use("/", purchaseOrders);
NOT
app.use("/purchaseOrders", purchaseOrders);
Other option
server.js:
app.use("/addpo", purchaseOrders);
purchaseOrders.js
router.post("/", function(req.res){
If you add a route before calling a router it will be added in front of it.
So, yo can use the route action="/addpo"
in the html.