Cannot Post to route - node.js

I am implementing a simple signup / login functionality in node js
But when using postman to post the router to localhost:3000/api/chatapp/register i am gettig error message
Cannot POST /api/register
CODE:
server.js
const express=require('express');
const mongoose=require('mongoose');
const cookiePaser=require('cookie-parser');
// const logger=require('morgan');
const app=express();
const dbConfig= require('./config/secret');
//adding middleware
app.use(cookiePaser()); //save our token in the cookie
// app.use(logger('dev')); // to display the url and http status code in the console
mongoose.Promise = global.Promise;
mongoose.connect(
dbConfig.url,{useNewUrlParser: true, useUnifiedTopology: true}
);
const auth=require('./routes/authRoutes');
app.use(express.json({limit: '50mb'})); //data coming in from form is limited up to 50 mb size
app.use(express.urlencoded({ extended: true, limit:'50mb'}));
app.use('/api/chatapp',auth);
app.listen(3000, () => {
console.log('Running on port 3000');
})
authRoute.js
const express=require('express');
const router=express.Router();
const AuthCtrl=require('../controllers/auth');
router.post('/register',AuthCtrl.CreateUser);
module.exports=router;
auth.js
module.exports={
CreateUser(req,res){
console.log(req.body);
}
};
userSchema.js
const mongoose = require("mongoose");
const userSchema = mongoose.Schema({
username: { type: String },
email: { type: String },
password: { type: String },
});
module.exports=mongoose.model('User',userSchema);
nodemon server and mongod are running fine
Postman result
for further details kindly look into my github repo :
https://github.com/Umang01-hash/chatApp-backend

Are you sure if that's the correct endpoint? Check out the folder structure and see this image for your answer.

Related

Post request isn't working in node.js express/mongoose

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}`));

How to post some json data to a route in api

I've created a very simple API in NodeJs. Here is the code:
const Post = require('../models/article');
...
router.post('/contribute', (req, res) => {
console.log('Pushing new article');
let userPost = req.body;
let post = new Post(userPost);
post.save((error, registeredPost) => {
if (error) {
console.log(error);
} else {
res.status(200).send(registeredPost);
}
})
})
...
module.exports = router;
The structure of a Post is this:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const articleSchema = new Schema({
articleid: String,
title: String,
content: String,
date: String,
contributor: String,
upvotes: Number,
upvoters: [String],
downvotes: Number,
downvoters: [String]
})
module.exports = mongoose.model('article', articleSchema, 'articles');
Here is server.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const api = require('./routes/api');
const cors = require('cors');
app.use(bodyParser.json());
app.use(cors());
app.use('/api', api);
app.get('/', function(req, res) {
res.send('Server is up and running!');
})
app.listen((3000), function() {
console.log('Server listening on heroku environment port');
});
Ideally the data should come from an angular form/template but before pushing the code I wanted to test this on Postman. Here is the screenshot:
I'm getting:
Cannot POST /contribute
Please point out my mistake.
Because you are using:
app.use('/api', api)
So, make sure to use this endpoint:
localhost:3000/api/contribute
And now, it's will working fine.
I didn't notice that I'm hitting the wrong URL.
Wrong:
localhost:3000/contribute
Correct:
localhost:3000/api/contribute
This is working absolutely fine now and I'm getting correct json response from the server also.

node js express mongoose api save operation not working

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;

save item in mongoose and monoDB

I'm trying to connect to my mongoDB and to save a new user inside.
When I run the express server, the db is connected but the post request doesn't seem to happen.
Can someone check my code and help me find the problem?
**when I send the request on postmam, the postman ends up with: 'could not get response, error:socket hang up'.
I'm attaching my code below:
my server:
const express = require('express')
const app = express();
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const authRoute = require('./routes/aouth')
dotenv.config();
//conect to db
mongoose.connect(mongodb://localhost/users, { useUnifiedTopology: true, useNewUrlParser: true }, () => console.log("connected!"))
//middleware
app.use(express.json());
//route middleware
app.use('/api/user', authRoute);
app.listen(3000, () => console.log("listening on port 3000!"))
my User.js:
const mongoose = require('mongoose')
const userSchema = new mongoose.Schema({
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model('User', userSchema);
my router (routes/aouth.js) :
router.post('/reg', async(req, res) => {
const user = new User({
password: req.body.password
})
try {
const savedUser = await user.save()
res.status(201).json(savedUser)
} catch (err) {
res.status(400).json({ message: err.message })
}
})
on postman my request is:
POST http://localhost:3000/api/user/reg
{
"password":"1234"
}
hope you guys can help me!!
Thank you!!
At a glance, I noticed that the path imported is wrong.
const authRoute = require('./routes/aouth')
Shouldn't it be?
const authRoute = require('./router/auth')
To be sure that you are connected to the database add the following lines.
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
You have to add this code to your server.
app.use(express.urlencoded({extended: false}))
It will work.
Extending #Daryl Answer, #Shir: As you mentioned routes folder name is correct.
But you have a file named auth.js & in your server file, you are importing aouth.
Please verify, you have correct import filename specified in server file, Else this could be an import path issue.

nodejs express route resulting in error 404

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

Resources