Reputation: 27
I have problem with routes, namely I have this error. POST http://localhost:4000/routes/api/user/register 404 (Not Found)
This is my server.
const express = require("express");
const path = require("path");
const config = require("./../server/config");
const cors = require("cors");
const isDev = process.env.NODE_ENV !== "production";
const port = process.env.PORT || 4000;
const app = express();
app.use(express.static(path.join(__dirname, "client/build")));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());
const registerRouter = require("./routes/api/user");
app.use("/user", registerRouter);
app.listen(port, () =>
console.log(`Example app listening at http://localhost:${port}`)
);
module.exports = app;
And this is my route:
const router = require("express").Router();
router.route("/register").post((req, res, next) => {
const { body } = req;
const { password, name } = body;
let { email } = body;
return res.send({
success: true,
message: "Signed up",
});
});
module.exports = router;
Lastly this is how I handle post request
const onSubmitHandler = (e) => {
e.preventDefault();
fetch("http://localhost:4000/routes/api/user/register", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
})
.then((res) => {
if (res.success) {
console.log(res.message);
}
})
.catch((err) => {
console.log(err);
});
};
This is structure of my project
server/routes/api/user
src/
Where is the problem ?
Upvotes: 1
Views: 85
Reputation: 429
Try this one
app.use(registerRouter);//first change here
then in router use this
const express = require("express");
const router = new express.Router();
router.post("/register", (req, res, next) => {
const { password, name, email } = req.body;
console.log('your message!!!')
res.send({
success: true,
message: "Signed up",
});
});
module.exports = router;
use this url in fetch http://localhost:4000/register
Upvotes: 1