I have tried to post in MongoDB by using postman while posting a text i got a error of (Couldnt get any Response) It is not showing any error to Command nodemon Please help me where i did mistake ..! what i need to do ?
My index.js file is:-
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const config = require('./configdb/database');
// Connection to database
mongoose.connect(config.database);
// Connection Success to DB
mongoose.connection.on('connected',() => {
console.log('Connected to the Database ' +config.database);
});
//on Error while Connecting
mongoose.connection.on('error',(err) => {
console.log('connection ERROR Try Again Database Failed to Connect ' +err);
});
const app = express();
const articles = require('./routers/articles');
// Port to start
const port = 2200;
// cors middleware
app.use(cors());
// Set Static Public folder
app.use(express.static(path.join(__dirname, 'public')));
// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
app.use('/articles',articles);
// Index Route
app.get('/', (req, res) => {
res.send('this is initial page for starting all session')
});
app.listen(port, () => {
console.log('server started in' + port)
})
my articles.js file is
const express = require('express');
const router = express.Router();
const config = require('../configdb/database');
const Article = require('../models/article');
// Register of article
router.post('/new-article', (req,res,next) => {
let article = new Article();
article.title = req.body.title;
console.log(req.body.title);
return;
article.save(function(err){
if(err){
res.json({success: false, msg: 'Failed to Register the Article' });
} else {
res.json({success: true, msg: 'New Article is Registered'});
}
});
});
module.exports = router;
my article.js file is
const mongoose = require('mongoose');
const config = require('../configdb/database');
const ArticleSchema = mongoose.Schema({
title:{
type: String,
}
});
const Article = module.exports = mongoose.model('Article', ArticleSchema)
But I have got the message from
article.title = req.body.title; and my error as follows:-
In articles.js you have return the function after displaying title cause the problem!
// Register of article
router.post('/new-article', (req, res, next) => {
let article = new Article();
article.title = req.body.title;
console.log(req.body.title);
// return;
article.save(function (err) {
if (err) {
res.json({
success: false,
msg: 'Failed to Register the Article'
});
} else {
res.json({
success: true,
msg: 'New Article is Registered'
});
}
});
});
Related
I'm new in couchbase and I'm using ottoman framework. I connected the database using ottoman and I create the schema and model User and exported it into controller file. When I create a new instance for that model, ottoman throw an error TypeError: User is not a constructor.
I search so many time and I red the official and non official documents and test it severely. I wrote all about the db in separate file and no change. I'll attach the file below it . But I didn't get any solution. please let me know...
const ottoman = require("ottoman");
exports.connect = async () => {
try {
await ottoman.connect({
connectionString: process.env.DB_CONNECTION_STRING,
bucketName: process.env.DB_BUCKET,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
});
console.log("Database connected.");
await ottoman.start();
} catch (error) {
console.log("Database not connected due to: ", error.message);
}
};
connect();
const User = ottoman.model("User", {
firstName: String,
lastName: String,
email: String,
tagline: String,
});
const perry = new User({
firstName: "Perry",
lastName: "Mason",
email: "perry.mason#example.com",
tagLine: "Who can we get on the case?",
});
const tom = new User({
firstName: "Major",
lastName: "Tom",
email: "major.tom#example.com",
tagLine: "Send me up a drink",
});
main = async () => {
await perry.save();
console.log(`success: user ${perry.firstName} added!`);
await tom.save();
console.log(`success: user ${tom.firstName} added!`);
};
main();
This issue happened due to disorder of functions calling in app.js file. All I used till now was a Mongodb and mongoose in noSQL. In the case of mongodb we can call the database config function after api endpoint specification. I wrote my code like this in couchbase. But it didn't stick in couchbase. I'll provide my code before and after fixing for more clarity, and I'm very sorry for my bad english. :)
Before fixing app.js file:
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const app = express();
require("dotenv").config();
const PORT = process.env.PORT || 3000;
//middlewares
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// routes
app.use("/api/", require("./routes/index"));
// bad requiest
app.use("*", (req, res) => {
res.status(404).json({ message: "Bad Requist." });
});
// error middleware
const { errorHandler } = require("./middlewares/error-middleware");
app.use(errorHandler);
// database setup
const db = require("./config/db");
db.connect();
// server setup
app.listen(PORT, (err) => {
if (err) {
console.log(err.message);
} else {
console.log(`The server is running on: ${PORT}.`);
}
});
After fixing app.js file:
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const app = express();
require("dotenv").config();
const PORT = process.env.PORT || 3000;
//middlewares
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// database setup
const db = require("./config/db");
db.connect();
// routes
app.use("/api/", require("./routes/index"));
// bad requiest
app.use("*", (req, res) => {
res.status(404).json({ message: "Bad Requist." });
});
// error middleware
const { errorHandler } = require("./middlewares/error-middleware");
app.use(errorHandler);
// server setup
app.listen(PORT, (err) => {
if (err) {
console.log(err.message);
} else {
console.log(`The server is running on: ${PORT}.`);
}
});
I tried to make simple application with login and middleware.
const express = require('express');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const cors = require('./services/CORS.service');
const authorization = require('./middleware/auth');
const loginRouter = require('./login/login.routes');
const usersRouter = require('./users/users.routes');
const app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(cors);
app.use('/login', loginRouter);
app.use('/users', authorization, usersRouter);
const PORT = 5000;
app.listen(PORT, () => {
console.log(`Node app is running in: http://localhost:${PORT} ..`);
});
module.exports = app;
like you can see, I have login router and users with middleware router.
This is the loginRouter:
const express = require('express');
const router = express.Router();
const _ = require('lodash');
const cryptoService = require('../services/crypto/service');
router.post('/login', login);
async function login(req, res, next) {
try {
const { account, session } = await controller.login(req.body);
if (!req.body.username || !req.body.password) {
throw { message: 'Missing BasicAuth user and password', status: 400 };
}
const encryptedPassword = cryptoService.encrypt(password);
const toEncrypt = JSON.stringify({username: username, password: encryptedPassword, timestamp: new Date()});
const session = cryptoService.encrypt(toEncrypt);
res.status(200).send({ session });
}
catch (err) {
const errMessage = _.get(err, 'message', 'error occurred');
const errCode = _.get(err, 'status', 500);
res.status(errCode).json({ message: 'error occurred', error: errMessage });
}
}
module.exports = router;
and this is the middleware:
const _ = require('lodash');
const cryptoService = require('../services/crypto/service');
const moment = require('moment');
const SESSION_TOKEN_EXPIRATION_IN_MINUTES = 50;
module.exports = async function (req, res, next) {
try {
const session = _.get(req, 'headers.session');
console.log(session);
let decryptedSession = '';
try {
decryptedSession = cryptoService.decrypt(session);
}
catch (err) {
throw { message: 'Session is not valid, please re-login', status: 401 };
}
if (!decryptedSession) {
throw { message: 'No session provided, please re-login', status: 401 };
}
const { username, password, timestamp } = JSON.parse(decryptedSession);
if (!timestamp || moment.duration(moment().diff(timestamp)).asMinutes() > SESSION_TOKEN_EXPIRATION_IN_MINUTES) {
throw { message: 'Session expired, please re-login', status: 401 };
}
res.locals = res.locals || {};
res.locals.account = account;
next();
}
catch (err) {
const errMessage = _.get(err, 'message', 'error occurred');
const errCode = _.get(err, 'status', 500);
res.status(errCode).json({ message: 'error occurred during auth validation', error: errMessage });
}
};
when the application running, I sending postman post request to login with username and password in the body.
I got a correct session.
but when I open the users page I got error:
No session provided, please re-login
because the session in the middleware is undefined.
what can I do to fix this code?
tnx
I'm a newbie in Nodejs and I'm coding a to-do app as a practical exercise. I'm having a problem that I cannot return to my index page "/" after using the DELETE method in Express. I use the deleteMany() of Mongoose to delete my docs, however after deleted all of those docs I couldn't return to the "/" page, the system threw an error in the console:
DELETE http://localhost:3000/ 404 (Not Found)
although using res.redirect("/") is fine with POST method. I've found a guy with the same problem as mine on Stack Overflow, but his solutions are not working in my app. Another solution of him is using pure Javascript to redirect from the client, however I want to do this job in the severside.
My files:
routes.js
module.exports = function(app) {
var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology: true});
var db = require("./db");
app.get("/", function(req,res,next) {
db.task.find()
.then(tasks => {
res.render("index", {tasks: tasks})
});
})
}
controller.js
module.exports = function(app) {
const routes = require("./routes.js");
const apiRoutes = require("./api.js");
app.use(function(req,res,next) {
console.log(`GET ${req.url}`);
next();
})
app.use("/api", apiRoutes);
routes(app);
}
api.js
var express = require("express");
var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var router = express.Router();
const mongoose = require("mongoose");
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology: true});
var db = require("./db");
router.post("/post", urlencodedParser, function(req,res) {
new db.task({"name": req.body.item, "status": "incompleted"})
.save(err => {
if (err) throw err;
console.log(req.body.item);
});
res.redirect("/");
}).delete("/delete/:item", function(req,res) {
var result = [];
var item = req.params.item;
//Config the url task to its original name
var delTask = item.replace(/\-/g," ").replace(/;/g,"-");
//Logging out the deleted task
db.task.find({"name": delTask}).then((foundTasks) => {
foundTasks.forEach(function(tasks){
var removedDoc = {"name": tasks.name, "Object_Id": tasks._id};
result.push(removedDoc);
})
})
db.task.deleteMany({"name": delTask}, (err) => {
if (err) throw err;
console.log("Removed items: ", result);
})
res.redirect("/");
})
module.exports = router;
You don't have to worry about the db.js file, because it just help me to create mongoose schema and completely do nothing with http or express. And finally the controller.js will be required in the app.js.
On localhost:5000/posts my data is successfully showing but if I do the same thing in Heroku: https://rest-in-peep.herokuapp.com/posts I get an application error. https://rest-in-peep.herokuapp.com/ works fine and I deployed it through Heroku GIT. I made sure to config my environmental vars in Heroku and added a Procfile but I am still getting this application error. I've been trying all day to figure this out but what I expect to happen is if I type in https://rest-in-peep.herokuapp.com/posts, I will get all the data that is being stored on my MongoDB database.
app.js file
const http = require("http");
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
require("dotenv/config");
const app = express();
const server = http.createServer(app);
//Middlewares
app.use(cors());
app.use(bodyParser.json());
//Import Routes
const postsRoute = require("./routes/posts");
app.use("/posts", postsRoute);
//ROUTES
app.get("/", (req, res) => {
res.send("We are on home");
});
//Connect to DB
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true },
() => console.log("connected to MongoDB")
);
//How do we start listening to the server
server.listen(process.env.PORT || 5000, () => {
console.log("App now running on PORT");
});
routes>
posts.js
const express = require("express");
const Post = require("../models/Posts");
const router = express.Router();
//GETS BACK ALL THE POSTS
router.get("/", async (req, res) => {
try {
const posts = await Post.find();
res.json(posts);
} catch (err) {
res.json({ message: err });
}
});
//SUBMITS A POST
router.post("/", async (req, res) => {
console.log(req);
const post = new Post({
quote: req.body.quote
});
try {
const savedPost = await post.save();
res.json(savedPost);
} catch (err) {
res.json({ message: err });
}
});
//SPECIFIC POST
router.get("/:postId", async (req, res) => {
try {
const post = await Post.findById(req.params.postId);
res.json(post);
} catch (err) {
res.json({ message: err });
}
});
//Delete Post
router.delete("/:postId", async (req, res) => {
try {
const removedPost = await Post.remove({ _id: req.params.postId });
res.json(removedPost);
} catch (err) {
res.json({ message: err });
}
});
//Update a post
router.patch("/:postId", async (req, res) => {
try {
const updatedPost = await Post.updateOne(
{ _id: req.params.postId },
{
$set: { quote: req.body.quote }
}
);
res.json(updatedPost);
} catch (err) {
res.json({ message: err });
}
});
module.exports = router;
gitignore
/node_modules
models>Posts.js
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
quote: {
type: String,
required: true
}
});
module.exports = mongoose.model("Posts", PostSchema);
I'm new at using back-end code.
I'm trying to Insert basic line into MongoDB online DB.
These are my files:
server.js:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
var db = require('./config/db');
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => {
if (err) return console.log(err);
db = database.db('note-api');
require('./app/routes')(app, db);
require('./app/routes')(app, database);
app.listen(port, () => {
console.log('We are live on ' + port);
});
})
note_routes.js:
module.exports = function (app, db) {
// const collection =
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').insert(note, (err, result) => {
if (err) {
res.send({ 'error': err });
} else {
res.send(result.ops[0]);
}
});
});
};
db.js:
module.exports = {
url: "mongodb://laelav:laelav1#ds227594.mlab.com:27594/getremp"
};
Whenever i try using POST and wish to update the online DB - I get an unauthorized error:
unauthorized error
Then I added this line in note_routes.js:
db.grantRolesToUser("laelav", [{ role: "readWrite", db: "getremp" }]);
And got the following "TypeError: db.grantRolesToUser is not a function":
not a function error
Please help!