Today when require a post in my server (Local) with a base64 image are returning this error:
Frontend are using AngularJS
Backend using MongoDB,Node.JS,Mongoose and NodeRestFULL
Front
Error backend
Here my server.js
const express = require('express')
const server = express();
//transform params to int
const queryParser = require('express-query-int')
//const allowCors = require('./cors')
server.use(function(req,res,next){
res.header('Access-Control-Allow-Origin','*')
res.header('Access-Control-Allow-Methods','GET,POST,OPTIONS,PUT,PATCH,DELETE')
res.header('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type, Accept')
res.header('Access-Control-Allow-Credentials', true);
next()
})
server.use(queryParser())
server.use(bodyParse.text({type:'*/*'}))
server.use(bodyParse.urlencoded({limit: '50mb', extended: true}))
server.use(bodyParse.json({type:'json/*', limit: '50mb'}))
//server.use(bodyParse.urlencoded({limit: '50mb'}));
server.listen(port, function(){
console.log(`BACKEND está rodando na porta ${port}`)
})
module.exports = server
loader.js
const server = require('./config/server')
require('./config/database')
require('./config/routes')(server)
Here my schema for mongodb
const restful = require('node-restful')
const mongoose = restful.mongoose
//Schema para os comprovantes
const reciboProventoSchema = new mongoose.Schema({
name: { type: String, required: true},
month: { type: String, required: true},
description: { type: String, required: true},
imgBase: {type: String, required: true}
})
module.exports = restful.model('BillsPaysProv', reciboProventoSchema)
Here i'll make basic services
//Import schemas
const BillsPaysProv = require('./billsProv')
//Create service to post a mensage contact
BillsPaysProv.methods(['get','put','post','delete'])
BillsPaysProv.updateOptions({new: true, runValidators: true})
module.exports = BillsPaysProv
Related
To start with I am noob in node.js and MongoDb and working with tutorial with Lama Dev social media as a basic project kindly help
in Postman
error 404 is coming
where in the video it's 200 ok
I have copied main code for 100-1000 times help
This Is my auth.js file
//auth.js
const router = require("express").Router();
const User = require("../models/User");
//register
router.post("/register", async (req, res) =>{
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password,
});
try{
const user = await newUser.save();
res.status(200).json(user);
} catch(err) {
console.log(err);
}
});
module.exports = router;
This Is my User.js file in models folder
//User.js
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
username: {
type: String,
require: true,
min: 3,
max: 20,
unique: true,
},
email: {
type: String,
required: true,
max: 50,
unique: true,
},
password: {
type: String,
required: true,
min: 6,
},
profilePicture: {
type: String,
default: "",
},
coverPicture: {
type: String,
default: "",
},
followers: {
type: Array,
default: [],
},
followings: {
type: Array,
default: [],
},
isAdmin: {
type: Boolean,
default: false,
},
}, {timestamps: true});
module.exports = mongoose.model("User", UserSchema);
This Is my index.js file
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const helmet = require("helmet");
const morgan = require("morgan");
const userRoute = require("./routes/users");
const authRoute = require("./routes/auth");
dotenv.config();
mongoose.connect(process.env.MONGO_URL, ()=> {
console.log("MongoDb Connected");
});
//middleware
app.use(express.json());
app.use(helmet());
app.use(morgan("dev"));
app.use("/api/users", userRoute);
app.use("/api/auth", authRoute);
app.listen(8800, ()=>{
console.log("Backhend server is running");
})
And this is a screenshot of postman
Postman ScreenShot Click here
Your POSTMAN screenshot shows your HTTP verb being GET, but the route your registered is using POST. Try changing the verb in POSTMAN.
I'm trying to post data in my MongoAtlas using Mongoose on Express and NodeJS. But Postman is returning a empty array. What I'm doing wrong
Database: mongodb+srv://username:password#clusterName.8xpcg.mongodb.net/databaseName?retryWrites=true&w=majority
Here are the FilesServer.js
const express = require('express');
const server = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv/config');
server.use(bodyParser.json());
//Importing Routes
const mcqRoutes = require('./routes/mcq');
const { application } = require('express');
//Routes
server.use('/mcq', mcqRoutes);
//DB Connection
mongoose.connect('mongodb+srv://<username>:<password>#<clusterName>.8xpcg.mongodb.net/<databaseName?retryWrites=true&w=majority', ()=>
console.log('DB Connected')
)
//Server Listening Port
server.listen(6969);
MCQ Route File
const express = require('express');
const router = express.Router();
const mcq = require('../models/mcq');
router.get('/', (req, res)=> {
res.send('We are on MCQS Homepage');
})
router.post('/', async (req, res)=> {
const Mcq = new mcq ({
"_id": req.body._id,
"m_title": req.body.m_title,
"m_slug": req.body.m_slug,
"m_question": req.body.m_question,
"m_alternatives": req.body.m_alternatives,
"m_number": req.body.m_number,
"m_subject": req.body.m_subject,
"m_language": req.body.m_language
});
try {
const saveMcq = await mcq.save();
res.json(saveMcq);
} catch(err){
res.json({ message: err});
}
})
module.exports = router;
MCQ Model
const mongoose = require('mongoose');
const McqScheme = mongoose.Schema({
_id: {type: Number, require: true},
m_date: {type: Date, default: Date.now},
m_title: {type: String, require: true},
m_slug: {type: String, require: true},
m_question: {type: String, require: true},
m_alternatives: {type: Array, require: true},
m_number: {type: String},
m_class: {type: String},
m_subject: {type: String},
m_type: {type: String},
m_board: {type: String},
m_paper: {type: String},
m_unit: {type: String},
m_language: {type: String},
});
module.exports = mongoose.model('mcq', McqScheme);
PostMan Response
In MCQ Router File Try Block has mcq.save(); in wrong Case.
After that I got buffering timed out after 10000ms Error. In Server.js File I add code in mongoose.connect. mongoose.connect(process.env.DB_CONNECTION, { useNewUrlParser: true, useUnifiedTopology: true}) .then(() => console.log("Database connected!")) .catch(err => console.log(err)); and also update my IP Address in MongoAtlas
I am getting a timeout error when I try to make a POST request to the database:
MongooseError: Operation `sessions.insertOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (/Users/don-alexantoine/Desktop/BCC-Website/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:185:20)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
This all started when I placed the routes into a different file. I don't what this why this is happening. I created API endpoints in the same manner and they work. Any help will be appreciated. Thanks in advance.
Here is the code:
Router.js file
const express = require('express');
const Session = require('../models/sessions')
const router = new express.Router();
router.get('/', (req, res)=>{
res.render('home');
});
router.post('/',async (req, res)=>{
try{
const session = new Session({
session_name: req.body.session_name,
first_name: req.body.fname,
last_name: req.body.lname,
room: req.body.room,
max_capacity: req.body.max,
session_time: req.body.time
});
console.log(session)
const newsession = await session.save();
console.log(newsession)
res.redirect('/')
}catch(e)
{
console.log(e)
}
})
module.exports = router
Sessions.js file
const mongoose = require('mongoose');
const SessionSchema = new mongoose.Schema({
session_name:{
type: String,
required:[true, 'session name is required'],
trim: true
},
first_name:{
type: String,
required:[true, 'Speaker last name is required']
},
last_name:{
type: String,
required: [true, 'Speaker last name is required']
},
room:{
required: [true, 'Room name is required'],
type: String
},
max_capacity: {
required: [true, 'Room max capacity is required'],
type: Number,
},
session_time: {
required: [true, 'Session time is required'],
type: String
},
room_counts:[{
count:{
type: Number,
},
time:{
type: String
}
}]
});
const Session = mongoose.model('session', SessionSchema);
module.exports = Session;
Main app file (app.js)
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const hbs = require('hbs');
const bodyparser = require('body-parser');
const sessionRouter = require('./routers/session');
const app = express();
const viewPath = path.join(__dirname, '../views');
const partialsPath = path.join(__dirname, '../views/partials');
app.use(bodyparser.urlencoded({extended: true}));
app.use(express.static(path.join(__dirname, '../public')));
app.use(sessionRouter);
app.set('views', viewPath);
app.set('view engine', 'hbs');
hbs.registerPartials(partialsPath);
app.listen(3000 || process.env.PORT, ()=>{
console.log('server is listening on port 3000');
});
Mongoose.js file
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/bccDB', {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify:true});
After, looking into your code below are the mistakes that I have found out
const sessionRouter = require('./routers/session'); your need to change this to const sessionRouter = require('./routers/Router');
secondly, your app is not connected to MongoDB. you have created the file but you have never called that file. I would recommend you to make a connect function, export it and call it inside the app.js
Mongoose.js
const mongoose = require('mongoose');
function connectDB() {
mongoose.connect('mongodb://localhost:27017/bccDB', {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify:true});
}
module.exports = {
connectDB
}
and initializing it inside app.js
const { connectDB } = require('./mongoose')
// create a connection to mongodb
connectDB()
Also, you need to handle the initialization in a better way in order to avoid crashing your application because of DB errors.
i am new to MERN framework
try to use postman to test my get and post request. but keep getting this error SyntaxError: Unexpected token b in JSON at position 3
here is my schema -------------------------
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
firstname: {
type: String,
required: true
},
lastname: {
type: String,
required: true
},
sex: {
type: String,
required: true
},
age: {
type: Number,
required: true
},
password: {
type: String,
required: true
},
admin: {
type: Boolean,
default: true
}
});
module.exports = User = mongoose.model("user", UserSchema);
here is my route---------------------
const express = require("express");
const router = express.Router();
const User = require("../../models/user");
router.get("/", (req, res) => {
User.find()
.sort({ age: -1 })
.then(users => res.json(users));
});
router.post("/", (req, res) => {
const newUser = new User({
firstname: req.body.firstname
});
newUser.save().then(user => res.json(user));
});
module.exports = router;
here is my server------------------
const express = require("express");
const mongoose = require("mongoose");
const users = require("./routes/api/users");
const app = express();
app.use(express.json());
const db = require("./config/keys").mongoURI;
mongoose
.connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));
app.use("/api/users", users);
const port = 5000;
app.listen(port, () => console.log(`server started on port ${port}`));
please help!! stuck for whole day
You do not need express.json() for GET routes. So please try moving app.use(express.json()); to route file before POST request.
Also if you are using express version >= 4, please use app.use(bodyParser.json()) from body-parser package.
I've declared a file called commentSchema which has some fields:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const moment = require('moment');
var commentSchema = new Schema ({
comment_text: {type: String, required: true},
user_token: {type: String, required: true},
activity_id: { type: Schema.ObjectId, ref: 'Activity', required: true },
is_hidden: { type: Boolean, "default": false },
created_at: { type: Number, "default": moment().unix() },
updated_at: { type: Number, "default": moment().unix() }
})
module.exports = mongoose.model('Comment', commentSchema);
and this is my router file:
var Router = require('router');
var router = Router();
var express = require('express');
var app = express();
// importing Models
var userSchema = require('./models/userSchema.js');
var activitySchema = require('./models/activitySchema.js');
var commentSchema = require('./models/commentSchema');
// Parsing the informations get from the client
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
router.get('/comments', (req, res) => {
});
router.post('/comment', (req, res) => {
var newComment = {
comment_text: req.body.comment_text,
user_token: req.body.user_token,
activity_id: req.body.activity_id
}
console.log(newComment);
commentSchema.create(newComment, (err) => {
if (err){
console.log(err);
}
else{
console.log('DONE!');
}
})
})
module.exports = router;
I'm trying to send post request using POSTMAN but I get the following error:
Cannot read property 'comment_text' of undefined
From the documentation of router. It says you have to use following:
router.use(bodyParser.json())