I have a route to create a category and when I try to run it in postman it returns an error saying, "Cannot POST /api/category"
I have tried to run through my code again and again but I cannot see where is the problem.
Thank for your help in advance
My schema:
const mongoose = require("mongoose");
const CategorySchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
},
categoryName: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = Categories = mongoose.model("category", CategorySchema);
My route:
const express = require("express");
const router = express.Router();
const auth = require("../../middleware/auth");
const { check, validationResult } = require("express-validator");
const Category = require("../../models/Category");
// #route POST api/category
// #desc Create or update users category
// #access Private
router.post(
"/",
[auth, [check("categoryName", "Category name is required").not().isEmpty()]],
async (req, res) => {
console.log(categoryName);
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
}
);
module.exports = router;
this is the way my code is organized
Ok thanks to Molda I found the problem.
I was missing my route definition in my server.js file.
All good now, thank you for your help.
const express = require("express");
const connectDB = require("./config/db");
const app = express();
//Connect DB
connectDB();
// Init Middleware
app.use(express.json({ extended: false }));
app.get("/", (req, res) => res.send("API Running"));
// Define routes
app.use("/api/users", require("./routes/api/users"));
app.use("/api/auth", require("./routes/api/auth"));
app.use("/api/profile", require("./routes/api/profile"));
app.use("/api/category", require("./routes/api/category"));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
Related
Between my app and Postman I should be able to make an entry into MongoDB, but I get this.
TypeError: Cannot read property 'title' of undefined
This is the app.js file
const express = require('express');
const app = express();
const Mongoose = require('mongoose');
require('dotenv/config')
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute)
app.use('/posts', () => {
console.log('This is a middleware.')
})
app.get('/', (req, res) => {
res.send('We are at home')
})
//Connect to DB
Mongoose.connect(process.env.DB_CONNECTION)
.then(() => {
console.log('connected to DB')
})
.catch(err => {
console.log(err);
});
app.listen(3000);
This is the posts.js file
const express = require('express');
const router = express.Router();
const Post = require('../models/Post')
var fs = require('fs');
router.get('/', (req, res) => {
res.send('We are at posts')
})
router.post('/', (req, res) => {
const post = new Post({
title: req.body.title,
description: req.body.description
});
post.save()
.then(data => {
res.json(data);
})
.catch(err => {
res.json({message: err });
})
});
module.exports = router;
This file is the Mongoose Schema
const { json } = require('body-parser');
const mongoose = require('mongoose');
const PostSchema = mongoose.Schema({
title: {
type: JSON,
required: true
},
description: {
type: JSON,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Posts', PostSchema);
Then I'm trying to post to MongoDB, through the app with Postman
Hopefully this photo should suffice.
The app is running fine locally on port 3000 and I do believe I am connecting to the database. It seems like a format problem. I don't know if the schema needs to be in JSON somehow or a configuration of Postman needs to change, but I have tried every Postman setting and tried changing the schema to JSON. I also had the type in the Mongoose file as type: String
Add this in app.js for POST Request...
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
Add that middleware on top of your routes.
index.js
const express = require("express");
const app = express();
const cors = require("cors");
const db = require("./models");
app.use(express.json());
app.use(cors());
//Router
const userrouter = require("./routes/user");
app.use("./user", userrouter);
db.sequelize.sync().then(() => {
app.listen(3001, () => {
console.log("Hello I am server.");
});
});
user.js
const express = require("express");
const router = express.Router();
const { Users } = require("../models");
router.get("/", async (req, res) => {
const noOfUsers = await Users.fetchAll();
res.json(noOfUsers);
});
router.post("/", async (req, res) => {
const post = req.body;
await Users.create(post);
res.json(post);
});
module.exports = router;
users.js
module.exports = (sequelize,DataTypes)=>{
const user = sequelize.define("Users",{
name:{
type:DataTypes.STRING,
allowNull: false,
},
description:{
type: DataTypes.STRING,
allowNull: true,
},
phone:{
type: DataTypes.INTEGER,
allowNull: false,
},
});
return user;
};
I have users.js in models folder. Why am I getting Cannot GET/ when I run the server? I am using node.js and I have also installed cors, mysql2, sequelize and express.
If you look at your index.js file, you're using app.use("./user", userrouter); but it should be app.use("/user", userrouter);.
I am creating my first node js api using Mongoose and Express. Facing some issue when i try to post the data it does not work. Postman request never completes and data does not get saved. Please find attached code and help me figure out the issue. Also note that db connection gets established successfully.
//Post.js
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
title: {
type: "string",
required: true,
},
description: {
type: "string",
required: true,
},
date: {
type: "Date",
default: Date.now,
},
});
module.exports = mongoose.model("Posts", PostSchema);
// Posts.js => Routes
const express = require("express");
const Post = require("../models/post");
const router = express.Router();
router.get("/", (req, res) => {
res.send("Posts");
});
router.post("/", (req, res) => {
try {
console.log(req.body);
const post = new Post({
title: req.body.title,
description: req.body.description,
});
post
.save()
.then((data) => res.json(data))
.catch((err) => res.json(err));
} catch (error) {
console.log(error);
}
});
module.exports = router;
// app.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
require("dotenv/config");
const bodyParser = require("body-parser");
//Import Routes
const postRoute = require("./routes/posts");
//Middlewares
app.use(bodyParser.json());
//Routes
app.use("/posts", postRoute);
// Connect to db
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("connected to db !");
}
);
app.listen(3000);
UPDATE
Looks like something is wrong with db connection itself. Below is my connection string. I handled the mongoose connection on error and i get the error shown in screen shot.
mongodb://<dbuser>:<dbpassword>#ds023550.mlab.com:23550/roofapp
Just pasted your code here and is working fine for both post and get.
Are you able to complete the GET request?
How is your project structured?
Make sure you are importing the files correctly.
From your commented out file names you have Post.js with capital letter and you are importing posts. It seems that something is wrong in the imports.
Here is a working solution based on the code you've posted.
Files : app.js - Post.js - Router.js
app.js:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
// require("dotenv/config");
const bodyParser = require("body-parser");
//Import Routes
const postRoute = require("./Router");
//Middlewares
app.use(bodyParser.json());
//Routes
app.use("/posts", postRoute);
// Connect to db
mongoose.connect("mongodb://localhost/test",
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("connected to db !");
}
);
app.listen(3000);
Post.js
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
title: {
type: "string",
required: true,
},
description: {
type: "string",
required: true,
},
date: {
type: "Date",
default: Date.now,
},
});
module.exports = mongoose.model("Posts", PostSchema);
Router.js
const express = require("express");
const Post = require("./Post");
const router = express.Router();
router.get("/", (req, res) => {
res.send("Posts");
});
router.post("/", (req, res) => {
try {
console.log(req.body);
const post = new Post({
title: req.body.title,
description: req.body.description,
});
post
.save()
.then((data) => res.json(data))
.catch((err) => res.json(err));
} catch (error) {
console.log(error);
}
});
module.exports = router;
The route is not working. I been looking for the cause and I can't find where the problem is. I keep on getting 404 error on postman with the server running.
Here is my server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const items = require('./routes/api/items');
const app = express();
// Bodyparser Middleware
app.use(bodyParser.json());
// DB Config
const db = require ('./config/keys').mongoURI;
// Connect to Mongo
mongoose.connect(db, {useNewUrlParser: true} )
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
//Routes
app.use ('api/items', items);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
Here is the file containing the routes. Is located at /routes/api
const express = require('express');
const router = express.Router();
// Item Model
const Item = require('../../models/Item');
// #route GET api/items
// #desc Get All Items
// #access Public
router.get('/', (req, res) => {
Item.find()
.sort({ date: -1 })
.then(items => res.json(items));
});
module.exports = router;
File models/item.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const ItemSchema = new Schema({
name: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = Item = mongoose.model('item', ItemSchema);
404 status : Route Not found , the url you are trying that is not found
in your app js , add slash / before api
app.use('/api/items', items);
url will be :
http://localhost:5000/api/items
Please understand the basic routes first.
Here is https://expressjs.com/en/guide/routing.html
When you run app like that
http://localhost:3000
app is runnin exactly on this url. If you route somthing else like that "api/items" this means that
http://localhost:3000api/items.
So create any route firstly add a '/' and then it looks like
http://localhost:3000/api/items
I'm trying to create a simple REST api using Postman and the MERN stack
I have the following files
server.js, Item.js, items.js, keys.js
server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const items = require('./routes/api/items');
const app = express();
// BodyParser Middleware
app.use(bodyParser.json());
// DB Config
const db = require('./config/keys').mongoURI;
//Connect to Mongo
mongoose
.connect(db)
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
app.use('./api/items', items);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('server started'));
Item.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const ItemSchema = new Schema({
name:{
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = Item = mongoose.model('item', ItemSchema);
items.js
const express = require('express');
const router = express.Router();
const Item = require('../../models/Item');
router.get('/', (req, res) => {
Item.find()
.sort({ date: -1 })
.then(items => res.json(items))
});
module.exports = router;
keys.js
module.exports = {
mongoURI: 'mongodb://tset:tset123#ds241012.mlab.com:41012/mern_shopping'
}
The server connects and connects to the DB - I get the console logs.
In postman if I try the GET and the url http://localhost:5000 I get
Cannot GET /
If I try http://localhost:5000/api/items I get
Cannot GET /api/items
Change this
app.use('./api/items', items);
to
app.use('/api/items', items);
and for http://localhost:5000 , the root you have to define with
app.get('/', function (req, res) {})