Adam Hiatt
Adam Hiatt

Reputation: 3

Express Routes not functioning

I am trying to create a route to my users file as well as others but when I use postman to send a get request to https://localhost:3000/api/users I get a "Cannot GET api/users/ error.

I have tried putting the require statement into a variable and then passing it to the app.use() function. I also made sure the in my users.js file that the first parameter is only a "/". Also it is not just the users route it is all of my routes that do not work. Can someone see my mistake?

Here is the server.js file

const express = require("express");
const connectDB = require("./config/db");

const app = express();

//Connect DB

connectDB();

app.get("/", (req, res) => res.send("API Running"));

//define routes

const userRoute = require("./routes/api/users");

app.use("api/users", userRoute);
app.use("api/auth", require("./routes/api/auth"));
app.use("api/profile", 
require("./routes/api/profile"));
app.use("api/posts", require("./routes/api/posts"));

const PORT = process.env.PORT || 3000;

app.listen(PORT, () =>
  console.log(`Server started on port: ${PORT}
`)
);

And here is the users.js file, all of the other router files are similar just with different names.

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

// @route    get api/users
// @desc     test route
// @ access  Public

router.get("/", (req, res) => res.send("User Route"));

module.exports = router;

I also tried changing the last line in users.js to export default router but that just resulted in an unexpected token error. Thank you in advance for the help.

Upvotes: 0

Views: 884

Answers (2)

Akhil Tripathi
Akhil Tripathi

Reputation: 26

Just replace your line app.use("api/users", userRoute); to app.use("/api/users", userRoute); in server.js

Upvotes: 0

Alex Masinde
Alex Masinde

Reputation: 193

Add '/' before your route definitions in the server.js file. So your route definition for the users will be app.use("/api/users", userRoute). Do the same for all your route definitions

Upvotes: 2

Related Questions