index.js file
import dotenv from "dotenv";
import connectDB from './db/index.js' ;
import { app } from "./app.js";
dotenv.config({
path:'./env'
})
connectDB()
.then(()=>{
app.listen(process.env.PORT || 8000,(req, res)=>{
console.log(`server is running at port at ${process.env.PORT}`)
})
})
.catch((err)=>{
console.log(err)
})
app.js file
import express from 'express';
import router from './routes/user.routes.js'
const app = express();
// routes declaration
app.use("/api/user/register", router)
export {app}
user.routes.js file
import { Router } from "express";
import { registerUser } from "../controllers/user.controller.js";
const router = Router()
try {
router.route("/register").post(registerUser)
} catch (error) {
console.log("Error at user.routes", error)
}
export default router
user.controller.js
import { asyncHandler } from "../utils/asyncHandler.js"
const registerUser = asyncHandler( async (req, res) => {
res.status(200).json({
message: "OK",
})
})
export {
registerUser
}
I’m new to backend and trying to access json data message Ok, the server at port 8000 is running fine but at http://localhost:8000/api/user/register I’m getting error Cannot POST /api/user/register , I’m trying in PostMan and using POST method
2
Answers
I think you should use ‘http://localhost:8000/api/user/register/register
I think that might solve the issue
Else chng your middlewire to:
app.use(‘/api/user’,router)