nodemon app crashed - waiting for file changes - node.js

I am learning node.js on my own and I do not understand why I get that error "[nodemon] app crashed - waiting for file changes before starting..". I have the same code as the one on the tutorial. What can be wrong?
Thank you for your help!
const express = require('express');
const mysql = require('mysql');
//create connection
const db = mysql.createConnection({
host: 'localhost',
user : 'root',
password : '123456',
});
//connect
db.connect((err)=>{
if(err){
throw err;
}
console.log("mysql is CONNECTED");
});
const app = express();
app.get('/createdb',(req,res) =>{
let sql = 'CREATE DATABASE nodemysql';
db.query(sql,(err, result)=>{
if(err) throw err;
console.log(result);
res.send('database created');
})
})
app.get('/createdb',()=>{
console.log("server started on port 3000");
})
app.listen('3000',()=>{
console.log("server started on port 3000");
});

Make sure mysql is installed:
npm install mysql --save
Try console.error(err) followed by return:
var mysql = require("mysql");
var connection = mysql.createConnection({
host: "example.org",
user: "bob",
password: "secret"
});
connection.connect(function(err) {
if (err) {
console.error("error connecting: " + err.stack);
return;
}
console.log("connected as id " + connection.threadId);
});

Related

Node JS to SQL SERVER get null empty when i trying conect

var app = require('express')();
app.get('/', (req, res) => {
var sql = require("mssql");
// config for your database
var config = {
user: 'sa',
password: 'xxxxx',
server: 'xx',
database: 'formdangky',
port :'1443'
};
(async function () {
try {
let pool = sql.connect(config)
let result1 = await pool.request()
.query('select * from dondangky')
// console.dir(result1)
// send records as a response
res.send(result1);
} catch (err) {
res.send(err)
}
})();
sql.on('error', err => {
// error handler
console.log(err);
});
});
//start listening
var port = 3000;
app.listen(port, function () {
console.log('Application started on ' + new Date());
console.log("Listening on " + port);
});
When i trying code but then the result is empty end not show something
Node JS to SQL SERVER get null empty when i trying conect with mssql from Npm https://www.npmjs.com/package/mssql#asyncawait
to get reslut from database

NodeJS connection with MongoDB using Mongoose

I am trying to view mongodb collections (just to view) in browser URL by accessing localhost:4000/books
app.js code:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var Book = require("./book.model");
//mongo DB database connection: databse nmae is: example
var db = "mongodb://localhost:27017/example";
mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true });
const conSuccess = mongoose.connection
conSuccess.once('open', _ => {
console.log('Database connected:', db)
})
conSuccess.on('error', err => {
console.error('connection error:', err)
})
var port = 4000;
app.listen(port, function () {
console.log("app listening on port " + port);
});
//REST get
app.get('/', function(req,res){
res.send("happy to be here");
});
//work on here localhost:4000 works but not localhost?4000/books
//get all "books" collections
app.get('/books', function(req,res) {
console.log("get all books");
Book.find({})
exec(function(err, books){
if(err){
res.send("error has occured");
} else {
console.log(books);
res.json(books);
}
});
});
book.model.js
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var BookSchema = new Schema({
title: String,
author: String,
category: String,
});
module.exports = mongoose.model("Book", BookSchema);
and the mongodb server started in cmd propt
ran> node app
console displayed messages as
"app listening on port 4000
Database connected: mongodb://localhost:27017/example"
in URL, when I tried to access like this
localhost:4000/books
display error as
reference error: exec is not defined. why is that, please help on this issue. I am working on rectify this erro for 3 days and really stcuk on this without moving forward.
use . before exec just try like this
app.get('/books', function(req,res) {
console.log("get all books");
Book.find({}).exec(function(err, books){
if(err){
res.send("error has occured");
} else {
console.log(books);
res.json(books);
}
});
});

deprecation warning is getting while starting nodemon index.js in cli

getting an error like this
i am doing a simple node js project that connect with mongodb. how to resolve this issue.?
this is the error getting in the terminal
DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
listening to serve 8080
Could not connect to database: { MongoNetworkError: failed to connect to server [localhost:27017] on first connect
mongo connect(index.js)
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const config = require('./config/database');
mongoose.Promise = global.Promise;
mongoose.connect(config.uri, (err)=>{
if(err){
console.log('Could not connect to database: ', err);
}
else{
console.log('Connected to database: ' +config.db);
}
});
app.get('/', (req, res)=>{
res.send('<h1>hello world</h1>');
});
app.listen(8080, ()=>{
console.log('listening to serve 8080')
});
database.js in config folder
const crypto = require('crypto').randomBytes(256).toString('hex');
module.exports= {
uri: 'mongodb://localhost:27017/' + this.db,
secret:
'crypto',
db:
'login'
}
how to solve?
mongoose.connect(config.uri, {useNewUrlParser: true}, (err)=>{
if(err){
console.log('Could not connect to database: ', err);
}
else{
console.log('Connected to database: ' +config.db);
}
});
That should work, just needs an extra parameter

MongoError: socket hang up

I am trying to connect to the mongodb database on mongolabs(mlabs). I connect successfully when I run the code on my local computer and server.But When I run on my aws server I get this error database error { [MongoError: socket hang up] name: 'MongoError', message: 'socket hang up' }
Code trial.js:
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var mongojs = require('mongojs');
var db = mongojs('mongodb://user:pass#ds01312192.mlab.com:133492/database', ['mohd'], { ssl : true });
db.on('error', function (err) {
console.log('database error', err);
});
db.on('connect', function () {
console.log('database connected');
});
db.mohd.find({}, function (err, docs) {
if(err){
console.log("error");
}else{
console.log(docs+"found");
}
});
app.set('view engine','ejs');
app.get('/',function(req,res){
console.log("hi");
});
app.listen(9000,function(){
console.log("server strated");
});
// catch 404 and forward to error handler
module.exports = app;
Got connection error on Amazon Web Service server but successful on local computer.
Ok so I solved the issue it was due to ssl connect method just removed it and was solved.
Use Instead:
var db = mongojs('mongodb://user:pass#ds01312192.mlab.com:133492/database', ['mohd']);

node js getting db error as 'PROTOCOL_CONNECTION_LOST'

i have developed a chat application using node js and socket io. However it is working fine for 5 to 10 minutes. But after that i keep on getting error as
db error { [Error: Connection lost: The server closed the connection.] fatal: true, code: 'PROTOCOL_CONNECTION_LOST' }
I am using below given code for reconnection but it still gives me same error.
var app = require('express')();
app.set('port', process.env.PORT || 3000);
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = app.get('port');
var mysql = require('mysql');
var db_config = {
host : 'localhost',
user : 'root',
password : '',
database : 'chatapp'
};
var connection;
function handleDisconnect() {
connection = mysql.createConnection(db_config);
connection.connect(function(err) {
if(err) {
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000);
}
});
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') {
handleDisconnect();
} else {
throw err;
}
});
}
handleDisconnect();

Resources