I've started learning on MEAN development. I had setup my express server and also my mongodb connection. On running node server in terminal the server starts running and also the mongo was able to connect but the localhost:8081/api/videos is not loading. I cleared cache and cookies but still no solution. I am attaching the code below.
server.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const api = require('./server/routes/api');
// Port for express server
const port = 8081;
const app = express();
app.use(express.static(path.join(__dirname,'dist/mean')));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json);
app.use('/api', api);
app.get('*', (req,res)=> {
res.sendFile(path.join(__dirname, 'dist/mean/index.html'));
});
app.listen(port, function(){
console.log('Server running at localhost:' + port);
});
api.js
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Video = require('../models/video');
// Creating mongo db connection
const db = 'mongodb+srv://<username>:<password>#training-qfjgb.mongodb.net/test?retryWrites=true&w=majority';
mongoose.Promise = global.Promise;
mongoose.connect(db, { useUnifiedTopology: true, useNewUrlParser: true }, err => {
if(err) {
console.log('Error: '+err);
}
else {
console.log('Successfully connected to mongodb');
}
});
router.get('/videos', function(req, res){
console.log('Get request for all videos');
Video.find({}).exec(function(err, videos){
if(err)
{console.log('Error retrieving videos');}
else
{res.json(videos);}
});
});
module.exports = router;
video.js (This is for the schema)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Creating database schema
const videoSchema = new Schema({
title: String,
url: String,
description: String
});
// Creating model of database videoplayer as model and then exporting
module.exports = mongoose.model('video', videoSchema, 'videoplayer');
const db = 'mongodb+srv://username:password#training-qfjgb.mongodb.net/test?retryWrites=true&w=majority';
username:password should be changed.
admin:12345(as you using)
const db = 'mongodb+srv://username:password#training-qfjgb.mongodb.net/test?retryWrites=true&w=majority';
Check this part thoroughly , Whether the collection name, format of the text are given correctly
Related
Whenever I make a post request, it shows that message is not a constructor. Here message is a model that I made using mongoose.
And I am exporting this model through
module.exports = message and using this exported model in form_post.js file
my app.js file
const express = require('express');
const app = express();
const path = require("path");
const mongoose = require('mongoose');
const port = 3000;
const form_display = require('./routes/form_display');
const form_post = require('./routes/form_post');
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
//Backend Connection
mongoose.connect("mongodb://127.0.0.1:27017/sudeepkart", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
var db = mongoose.connection;
db.once("open", function () {
console.log("We are Connected !!");
});
// Pug Specific
app.set('view engine', 'pug') //Setting View Engine as Pug
app.set('views', path.join(__dirname, 'views')) //Setting views directory so that pug files can be fetched from he views directory
// Express Specific
app.use(form_display);
app.use(form_post);
app.use('/static',express.static('static'))
app.use((req, res, next)=>{res.status(404).send('<h2>Error Page Not found</h2>')});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
})
my form_post.js file
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Message = require('../models/message.model')
const port = 3000;
router.use(express.urlencoded({ extended: false }))
router.use(express.json())
router.post('/message', function (req, res) {
// Creating New Object
var newMsg = new Message(req.body);
newMsg.save(function (err, msg) {
});
res.send('Your message has been successfully submitted');
})
module.exports = router;
my models/message.model.js file
const mongoose = require('mongoose');
// New Schema and New Model
var message_schema = new mongoose.Schema({ "id":String, "message":String });
var message = new mongoose.model("message_model", message_schema); // in other words model is a synonym for collection
module.exports = message;
Try destructuring it:
const {message} = require('../models/message.models')
MDN Documentation for destructuring
To answer your comment question, because you're trying to import Message while only exporting message. On your module.exports, I would reccomend always doing module.exports = {variable1, function2} etc, so you can destructure it and you can easily debug any issues (and stop confusion with variables too!)
i'm trying to build a simple rest api based on node.js + mongodb
i'm using https://cloud.mongodb.com/ and my connection string is 1000% correct
i keep having this problem sometimes it work for me all the day no issue
and sometimes it doesn't wanna connect and i changed nothing in the code
anyone is having similar issues?
const mongoose = require('mongoose');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
require('dotenv/config');
app.use(bodyParser.json());
// Import routes
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);
//mongodb connect
mongoose.connect(process.env.db_access, { useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log('connected');
}
);
//ROUTES
app.get('/', (req,res) => {
res.send('home boi');
});
//listening port
app.listen(3000);
Hej people
I try to create some fullstack app (base on one tutorial) and I have some problem with understand how backed part work. Teoreticlly, then I did this tutorial first time, everything was working. But now, then I try to something new base on it, I see how many things I don't understand. Basically, why it won't work.
I generate express app. My app.js looks that:
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
var cors = require('cors');
mongoose.connect('mongodb://localhost/covid', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
}).then(() => console.log('connection successful'))
.catch((err) => console.error(err));
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var casesRouter = require('./routes/cases');
var app = express();
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/api', casesRouter);
module.exports = app;
routers/cases.js:
var express = require('express');
var router = express.Router();
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var Cases = require('../models/Cases.js');
server.listen(4000)
// socket io
io.on('connection', function (socket) {
socket.on('newdata', function (data) {
io.emit('new-data', { data: data });
});
socket.on('updatedata', function (data) {
io.emit('update-data', { data: data });
});
});
// list data
router.get('/', function(req, res) {
Cases.find(function (err, cases) {
if (err) return next(err);
res.json(cases);
});
})
module.exports = router;
and schema:
var mongoose = require('mongoose');
var CasesSchema = new mongoose.Schema({
id: String,
name: String,
location: String,
state: String,
});
module.exports = mongoose.model('Cases', CasesSchema);
ok, it's all.
So now I run it from my console by nodemon. In console everything looks ok. No error, and message that everything is ok. But app is not working:
1) I expect that this part:
mongoose.connect('mongodb://localhost/covid', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
}).then(() => console.log('connection successful'))
.catch((err) => console.error(err));
should created me now new schema "covid" with object Cases with keys id, name, location, state. It didn't happen. I installed Compass to easiest examination my mongodb and I can see, that I don't have something like covid. ok, I created it manually, But, as I understand, it should be done automaticlly after I run nodemon.
2) I expect that I can examination my backend via postman. https://localhost:3000/api/ (3000 - nodemon default port), but I
Could not get any response There was an error connecting to
https://localhost:3000/api/.
and it's everything. I can't see this error neither in console nor postman.
Maybe I don't understand something with ports in express app, or I don't understand something with mongoDB. But google didn't help me. It did only bigger mess in my head. So maybe someone of you can explain me how it should work and why?
I am a newbie in node.I have created a server file to connect mongoDB and wrote routes in the same. Created a model.js for table attributes.I want to write a route for my other tables.
https://codingthesmartway.com/the-mern-stack-tutorial-building-a-react-crud-application-from-start-to-finish-part-2/
Taken reference from here. But want to create a seperate file for connection and add module for tables
This is my server.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const todoRoutes = express.Router();
const PORT = 4000;
let Todo = require('./todo.model');
app.use(cors());
app.use(bodyParser.json());
app.use('/todos', todoRoutes);
mongoose.connect('mongodb://127.0.0.1:27017/todos', {
useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function() {
console.log("MongoDB database connection established
successfully");
})
app.listen(PORT, function() {
console.log("Server is running on Port: " + PORT);
});
todoRoutes.route('/').get(function(req, res) {
Todo.find(function(err, todos) {
if (err) {
console.log(err);
} else {
res.json(todos);
}
});
});
this routes are in this file i want to export it from other model.js
If you want to put route in another file,i would suggest you to make a new folder route and then inside it make a new file by route name(say createUser.js).
In this server.js file only use
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const PORT = 4000;
let Todo = require('./todo.model');
app.use(cors());
app.use(bodyParser.json());
app.use('/todos', todoRoutes);
mongoose.connect('mongodb://127.0.0.1:27017/todos', {
useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function() {
console.log("MongoDB database connection established
successfully");
})
app.listen(PORT, function() {
console.log("Server is running on Port: " + PORT);
});
export default app;
And in another file inside route folder use the require imports and define the route here.
const todoRoutes = express.Router();
todoRoutes.route('/').get(function(req, res) {
Todo.find(function(err, todos) {
if (err) {
console.log(err);
} else {
res.json(todos);
}
});
});
module.exports=todoRoute;
Furthur you can import this route in any model.js and use it for implementation of logic.
Note-: You can also use a third folder controllers and implement the route logic there since it is the best practice to not write logic on route but use controller file for it.Also you can separate the DB connection login in another file.
I'm new to Node/Express/Mongo/MLab and backend programming in general. I am trying to submit a post request to an MLab database and running into trouble. I think my problem is with Mongoose and MLab.
Here is my Glitch project
I'm getting error MongoDB connection error: { MongoError: Authentication failed. Why am I getting this error? Is there a problem with my mongoose.connect function and credentials? Is MLab not properly set up?
'use strict';
var express = require('express');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var validUrl = require('valid-url');
var dns = require("dns");
var cors = require('cors');
var app = express();
// Basic Configuration
var port = process.env.PORT || 3000;
// Hooks up app to MLab MongoDB database by using the .env variable I created
// Doesn't work. Data is not submitted to MLab and /api/shorturl/new endpoint freezes up when form is submitted
mongoose.connect(process.env.MONGODB_URI, {useMongoClient: true});
/*
Also doesn't work
mongoose.connect(process.env.MONGODB_URI, {
"auth":{"authSource": "admin"},
"user": "admin",
"pass": "password"
});
*/
// Should allow us to use promises with mongoose
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
// Sets up a Schema for the DB
var urlSchema = new mongoose.Schema({
url: String,
shortenedUrl: String
});
// Sets up a model for the DB
var Url = mongoose.model("Url", urlSchema);
app.use(cors());
/** this project needs to parse POST bodies **/
// you should mount the body-parser here
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use('/public', express.static(process.cwd() + '/public'));
// parse application/x-www-form-urlencoded
app.get('/', function(req, res){
res.sendFile(process.cwd() + '/views/index.html');
});
app.get("/api/shorturl/new", function (req, res) {
res.sendFile(process.cwd() + '/views/form.html');
//res.send({hi: "hi"});
});
app.post("/api/shorturl/new", urlencodedParser, function (req,res) {
// Gets URL from form
//var url = req.body.url;
//console.log(url);
var myData = new Url(req.body);
console.log("myData : " + myData);
myData.save()
.then(item => {
res.send("Successfully saved to DB");
})
.catch(err => {
res.status(400).send("Unable to save to DB");
});
});
app.listen(port, function () {
console.log('Node.js listening ...');
});
As other people have commented the code itself looks like it should work.
so the immediate suspect is the URI,
obviously you are not going to post the full string for all of us to see, but one theory that comes to mind is your password having characters that need encoding,
try using javascripts encodeURIComponent on the password.