Cannot GET / error using thunderclient to send request - javascript

I'm having trouble with my server routes. is there any problem with my routes? or a problem with the code?
I have checked all the possible question answers.
I'm having trouble with my server routes.
used thunderclient to send request
when I route it shows this
enter image description here
I tried to set thunder client POST to GET but got the same error
Index.js
const connectToMongo = require('./db');
const express = require('express')
connectToMongo();
const app = express()
const port = 5000
//Available Routes
app.use('/api/auth', require('./routes/auth'))
// app.use('./api/notes', require('./routes/notes'))
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
my auth.js where login and register exist.
const express = require('express');
const User = require('../models/User');
const router = express.Router();
const { body, validationResult } = require('express-validator');
// Create a User using: POST "/api/auth/". Doesn't require auth
router.post('/',[
body('name').isLength ({min: 3}),
body('email').isEmail(),
body('password').isLength ({min: 5})
], (req, res)=>{
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send(req.body);
})
module.exports = router
my user.js which shows user data
const mongoose = require('mongoose');
const {Schema}= mongoose;
const UserSchema = new Schema({
name:{
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password:{
type: String,
required: true
},
date:{
type: Date,
default: Date.now
},
});
module.exports = mongoose.model('user', UserSchema);

Related

Cannot POST / error using thunderclient to send request

I'm having trouble with my server routes. is there any problem with my routes? or a problem with the code?
I have checked all the possible questions & answers.
I'm having trouble with my server routes.
used thunderclient to send request
when I route it shows this
I tried to set thunder client POST to GET but got the same error
Index.js
const connectToMongo = require('./db');
const express = require('express')
connectToMongo();
const app = express()
const port = 5000
//Available Routes
app.use('/api/auth', require('./routes/auth'))
// app.use('./api/notes', require('./routes/notes'))
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
my auth.js where login and register exist.
const express = require('express');
const User = require('../models/User');
const router = express.Router();
const { body, validationResult } = require('express-validator');
// Create a User using: POST "/api/auth/". Doesn't require auth
router.post('/',[
body('name').isLength ({min: 3}),
body('email').isEmail(),
body('password').isLength ({min: 5})
], (req, res)=>{
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send(req.body);
})
module.exports = router
my user.js which shows user data
const mongoose = require('mongoose');
const {Schema}= mongoose;
const UserSchema = new Schema({
name:{
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password:{
type: String,
required: true
},
date:{
type: Date,
default: Date.now
},
});
module.exports = mongoose.model('user', UserSchema);
I tried to set thunder client POST to GET but got the same error
Is there any problem with my routes? or a problem with the code?

{error:{ }} is being returned in express js backend (mongodb)

I'm trying to POST Data to Mongo DB Using Express Js.
I'm new to express just learned for a backend server
This is my app.js
const express = require("express");
const mongoose = require("mongoose");
require("dotenv/config")
const User = require("./model/user.js")
let app = express();
app.use(express.json())
app.get("/", (req,res) => {
res.send("On Home!")
});
app.post("/register", async (req,res) => {
try {
const myUser = new User(req.body);
await myUser.save();
res.send(myUser);
} catch (err){
res.send({error : err});
}
});
mongoose.connect(process.env.DB_URI,(req,res) => {
console.log("Connected to Database!")
});
app.listen("5000" , () =>{
console.log("Listening on localhost 5000")
})
My user.js
const mongoose = require("mongoose");
const User = mongoose.Schema({
name: {
type: String,
required: true,
},
email:{
type:String,
required: true,
},
pass:{
type: String,
required: true,
}
});
module.exports = mongoose.model("user",User)
My Response Is
My Response
(I'm Using Postman to test)
Thank You For Your Support
You need to use body-parser, add this to your code:
var bodyParser = require('body-parser');
app.use(bodyParser.json());

MissingSchemaError: Schema hasn't been registered for model using execPopulate

i have spent quite some time going over the multiple solutions presented for this error and i have tried them but none seem to work for my case.
i'm trying to populate a field with details from it's collection.
This is everything
2 collections
sups
surgetypes
Code for sups & surgetypes is in folders with the same names
Route declaration & mongodb connection is in host/app.js
host > app.js
require('dotenv').config()
const express = require('express');
const mongoose = require('mongoose')
const morgan = require('morgan')
const app = express()
const cors = require('cors')
mongoose.connect(process.env.LB_DB_URL, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, autoIndex: false })
.then(() => {
console.log(`Logbook DB attached to <<< ${process.env.PORT} >>>`)
})
.catch((err) => {
console.error("Could not Attach DB because of::: \n \n ", err)
})
//cors
app.use(cors())
app.options('*', cors())
//middleware
app.use(express.json())
app.use(morgan('tiny'))
//SUB-APPS
const sups = require('../sups/app')
const surgetypes = require('../surgetypes/app')
app.use('/sups', sups);
app.use('/surgetypes', surgetypes)
module.exports = app;
sups > app.js
const express = require('express')
const supRoutes = require('./routes/index')
const app = express()
app.use("/", supRoutes)
module.exports = app
sups > models > index.js
const mongoose = require('mongoose')
const supSchema = new mongoose.Schema({
Jene: {
type: String,
required: true
},
typeOfSurge: {
type: mongoose.Schema.Types.ObjectId,
ref: 'surgeType',
required: true
}
})
module.exports = mongoose.model('sups', supSchema)
sups > routes > index.js
const { surgeType } = require('../../surgetypes/models/index')
const visor = require('../models/index')
const express = require('express')
const router = express.Router();
router.get('/:id', async (req, res) => {
const sup = await (await visor.findById(req.params.id).populate('typeOfSurge')).execPopulate()
res.status(200).json(sup)
})
module.exports = router
surgetypes > models > index.js
const mongoose = require('mongoose')
const surgeTypeSchema = new mongoose.Schema({
specialName: {
type: String,
required: true,
unique: true,
index: true
},
image: {
type: String,
required: true
}
})
exports.surgeType = mongoose.model('surgetypes', surgeTypeSchema)
What i'm trying to achieve is to to populate the details of a surgetypes collection document in the sups collection document when sending a >>> Get '/:id' <<< request
A surgetypes collection document is already referenced by it's id.
The error is
(node:4608) UnhandledPromiseRejectionWarning: MissingSchemaError: Schema hasn't been registered for model "surgeType".
Guys i'm laughing so hard right now.
So, the problem is
this line
typeOfSurge: {
type: mongoose.Schema.Types.ObjectId,
ref: 'surgeType',
required: true
}
the ref: 'surgeType'
should be ref:'surgetypes'
referencing the collection name
Oh the amount of hours i've dedicated to this.
The joy of programming Amirite?
Must be nice being an AI that programs with tried and tested rules.
Anyway, that was it.

node.js req.body returning undefined

EDIT: #LawrenceCherone solved this, its (req, res, next) not (err, res, req)
I am creating a MERN app (Mongo, express, react, node).
I have some routes that work fine and return data from mongodb. However I created a new controller to access a separate collection and whenever i try to create a new document in it my req.body returns undefined.
I have setup my server.js like this:
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const connectDB = require("./db");
const app = express();
const apiPort = 3000;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
app.use(bodyParser.json());
connectDB();
app.use("/api", require("./routes/router"));
var server = app.listen(apiPort, () => console.log(`Server running on port ${apiPort}`));
module.exports = server;
My router looks like this:
const express = require("express");
const QuizController = require("../controllers/quiz-controller");
const UserController = require("../controllers/user-controller");
const router = express.Router();
// quiz routes
router.post("/quizzes", QuizController.createQuestion);
router.get("/quizzes", QuizController.getAllQuestions);
router.get("/quizzes/:quiz_name", QuizController.getQuestionsByQuiz);
router.get("/quizzes/questions/:question_id", QuizController.getQuestionById);
router.put("/quizzes/:question_id/edit", QuizController.updateQuestionById);
router.delete("/quizzes/:question_id", QuizController.deleteQuestionById);
// user routes
router.post("/users", UserController.createUser);
module.exports = router;
All of the /quizzes routes work perfectly fine and i have had no trouble accessing the body. The UserController.createUser method is almost identical to Quizcontroller.createQuestion too so I am very confused.
Here is the user-controller with the createUser function:
const User = require("../models/User");
createUser = async (err, res, req) => {
const body = req.body;
console.log(req.body);
console.log(req.params);
console.log(body);
if (!body) {
return res.status(400).json({
succes: false,
error: "You must provide a body",
});
}
try {
const newUser = new User(body);
console.log(newUser);
if (!newUser) {
return res.status(400).json({ success: false, error: err });
}
const user = await newUser.save();
return res
.status(200)
.json({ success: true, newUser: user, msg: "New user created" });
} catch (err) {
console.error(err.message);
res.status(500).send("Server error");
}
};
module.exports = { createUser };
Here is an image of the postman request I am using to try test this:
[1]: https://i.stack.imgur.com/UHAK5.png
And the user model:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
emailAddress: {
type: String,
required: true,
},
permission: {
type: String,
required: true,
},
auth0Id: {
type: String,
required: true,
},
});
module.exports = mongoose.model("users", UserSchema);
The functional parameter order matters.
its
createUser = async (req, res, next) => // correct format
Not
createUser = async (err, res, req) // wrong format

Postman returns ' Could not get any response '

Postman returns ' Could not get any response ' when I send a Post request, but get a request to other URL works just fine. please how can I resolve this issue? index.js is the entry point to my application. the get URL below is working.
index.js
const express = require('express')
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const bodyParser = require('body-parser')
const app= express()
//body parser
app.use(bodyParser.json())
//config
dotenv.config()
//connect to db
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true },
()=>{
console.log('contented to db')
}
)
//import route
const authRoute = require('./ROUTES/auth')
app.use('', authRoute)
app.use('/api/user', authRoute)
//start server
app.listen(5000);
# auth.js #
all routings are done in auth.js
const express =require('express')
const router = express.Router();
const User = require('./moduls/User')
router.get('/',(req, res)=>{
res.send('home')
})
//validation schema
const joi =require('#hapi/joi');
const regSchema ={
name:joi.string().min(6).required(),
email:joi.string().required().email(),
password:joi.string().min(8).required()
}
router.post('/register', async(req, res)=>{
//check and return error status
const { error } = joi.ValidationError(regSchema);
if(error) return res.status(400).json({message: err})
const emailExist = await User.findOne(req.body.email)
if (emailExist) return res.status(400).json({message:'there is a user with this email'})
//get user object
const user =new User({
name:req.body.name,
email:req.body.email,
password:req.body.password,
rePassword:req.body.rePassword
})
try{
await user.save()
.then(data=>{
res.json(data)
})
}
catch(err){
res.status(400).json({message: err})
}
})
module.exports=router;
modules/User.js
user module in the modules folder
const mongoose = require('mongoose')
const userSchema =new mongoose.Schema({
name:{
type: String,
required:true,
min:6,
max:30
},
email:{
type: String,
required:true,
max:100
},
password:{
type:String,
required:true,
min:8
},
rePassword:{
type:String,
required:true,
min:8
},
date:{
type:Date,
default:Date.now()
}
})
module.exports = mongoose.model('User', userSchema)
The .save() function returns a promise that you can await. You don't need to use .then() when using async/await.
Instead of this.
await user.save()
.then(data=>{
res.json(data)
})
I'd do this.
const data = await user.save();
res.json(data);

Categories

Resources