Search code examples
node.jsexpressserverroutes

Browser not able to find Express Route URL Endpoint


When I use Postman or make a request in my browser to test my api routes I receive a 404 error in the browser console at users/:1 (no errors in server console). There is very little functionality in the app right now, just trying to follow a tutorial (Brad Traversy's React Front to Back course on Udemy) and get my routes set up and tested. I've reviewed all of the instructions up to this point and have checked my code against the completed codebase in the tutorial's GH repo, and it appears to be correct but I'm sure I'm missing something small. All dependencies have been installed and audited via NPM. Below is the code for:

server.js

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

const app = express();

//* Connect to database
connectDB();

//* Init Middleware
app.use(express.json({ extended: false }));

//*Define routes
app.use("/api/users", require("./routes/users"));
app.use("/api/auth", require("./routes/auth"));
app.use("/api/contacts", require("./routes/contacts"));

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

//*Initialize server
app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));

users.js

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

const User = require("../models/User");

//*     @route:     POST api/users
//*     @desc:      register a user
//*     @access:    Public
router.post("/", (req, res) => {
  res.send(req.body);
});

module.exports = router;

package.json

{
  "name": "openhousev2",
  "version": "0.1.0",
  "description": "Open Source Contact Management Platform\u001b[1;5D\u001b[1;5D\u001b[1;5D\u001b[1;5D\u001b[1;5D",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "server": "nodemon server.js"
  },
  "author": "LucSedirae",
  "license": "SEE LICENSE IN LICENSE",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "config": "^3.3.3",
    "express": "^4.17.1",
    "express-validator": "^6.8.1",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.11.8"
  },
  "devDependencies": {
    "concurrently": "^5.3.0",
    "nodemon": "^2.0.6"
  }
}

File structure

.
|-- server.js
|-- package.json
|-- __routes
    |-- users.js
    |-- auth.js
    |-- contacts.js
|-- __models
    |-- User.js
|-- __config
    |-- db.js
    |-- default.json

Solution

  • My issue was that in Postman, I was leaving the request type set to the default of "get" even though my route was for a post request. Changing they req type to POST simulated the posting of data through my route and worked as expected. The browser was not going to be an appropriate place to test my code to this point since I had nothing to post.