Getting Error while using Postman

I am trying to test an API that I saw in a video by freecodecamp. I have a script called “server.js” and under the directory of routes, I have “users.js” and a “user.model.js” script under a directory called “models”.

I ran a POST request through Insomnia using JSON (attaching the image).

Code for “server.js” is:

const express = require('express');

const cors = require('cors');

const mongoose = require('mongoose');

require('dotenv').config();

const app = express();

const port = process.env.PORT || 5000;

app.use(cors());

app.use(express.json());

const uri = process.env.ATLAS_URI;

mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true }

);

const connection = mongoose.connection;

connection.once('open', () => {

  console.log("MongoDB database connection established successfully");

})

app.listen(port, () => {

    console.log(`Server is running on port: ${port}`);

});

Code for “user.model.js” is:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const userSchema = new Schema({

  username: {

    type: String,

    required: true,

    unique: true,

    trim: true,

    minlength: 3

  },

}, {

  timestamps: true,

});

const User = mongoose.model('User', userSchema);

module.exports = User;

Code for “users.js” is:

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

let User = require('../models/user.model');

router.route('/').get((req, res) => {

  User.find()

    .then(users => res.json(users))

    .catch(err => res.status(400).json('Error: ' + err));

});

router.route('/add').post((req, res) => {

  const username = req.body.username;

  const newUser = new User({username});

  newUser.save()

    .then(() => res.json('User added!'))

    .catch(err => res.status(400).json('Error: ' + err));

});

module.exports = router;

Overall, I do not know where I committed the error. Did exactly what I was told. When I run the server.js, it says database connection is established successfully. (Cannot do that as there is a limit of posting more than one image but I did it accordingly)

Thanks in Advance!

I can’t see where you are importing routes in the server.js file.

Probably that is my error. Can you please kindly tell me what to include? Also are there other errors?

You need to import your users router in your server.js file. Use it after you define the express app and before you listen on a port.

const express = require('express');

const cors = require('cors');

const mongoose = require('mongoose');

require('dotenv').config();

const userRouter = require('./users.js')

const app = express();
....
// this tells express to use the routes defined in users.js whenever a request comes to an endpoint starting with '/users'
app.use('/users', userRouter); 
....
app.listen(port, () => {

    console.log(`Server is running on port: ${port}`);

});

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.