Table 'todoblog.users' doesn't exist - javascript

I'm trying to create a small todo blog using sequelize. But I get stacked in this error. The table is not created. I created the database using SQL, then I used sequelize in the model and controller.
schema.sql
(here I created a database and run it manually in the terminal)
DROP DATABASE IF EXISTS toDoBlog;
CREATE DATABASE toDoBlog;
USE toDoBlog;
connection.js
(Here when I'm connecting to the database)
// connection
const sequelize = new Sequelize("toDoBlog", "name", "password", {
host: "localhost",
dialect: "mysql",
host: "localhost",
});
// testing connection to database
sequelize
.authenticate()
.then(() => {
console.log("Connection has been established successfully.");
})
.catch((err) => {
console.error("Unable to connect to the database:", err);
});
module.exports = sequelize;
userModel.js
(creating the table and define it)
const Sequelize = require("sequelize");
const connection = require("../connexion/connexion.js");
const User = connection.define("user", {
user_id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
name: { type: Sequelize.STRING, allowNull: false },
email: { type: Sequelize.STRING, allowNull: false },
password: { type: Sequelize.STRING, allowNull: false },
createdAt: Sequelize.DATE,
updatedAt: Sequelize.DATE,
});
module.exports = User;
userController.js
(create/find/delete operations)
const UserModel = require("../database/Model/userModel.js");
module.exports.createOne = async (req, res) => {
const info = req.body;
console.log(info);
const user = await UserModel.create({
name: info.name,
email: info.email,
password: "hash(info.password)",
});
};
userRouter.js
(router for the controllers)
const userController = require("../controllers/userController.js");
var express = require("express");
var router = express.Router();
router.post("/createOne", userController.createOne);
module.exports = router;
index.js
(main file)
const express = require("express");
const bodyParser = require("body-parser");
const connextion = require("./database/connexion/connexion.js");
const userRouter = require("./routers/userRouter.js");
// const blogRouter = require("./routers/blogRouter.js");
const app = express();
const port = 3000;
app.get("/", (req, res) => {
res.send("express working");
});
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
// to link the front. I need to get more info about it.
app.use(express.static(__dirname + "/../react-client/dist"));
app.use("/api/user", userRouter);
// app.use("/api/blogs", blogRouter);
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
this is the error
[nodemon] starting `node server/index.js`
Example app listening at http://localhost:3000
Executing (default): SELECT 1+1 AS result
Connection has been established successfully.
{ name: 'SEMER', email: 'semer', password: 'smeer' }
Executing (default): INSERT INTO `users` (`user_id`,`name`,`email`,`password`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?);
C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\dialects\mysql\query.js:256
return new sequelizeErrors.DatabaseError(err);
^
DatabaseError [SequelizeDatabaseError]: Table 'todoblog.users' doesn't exist
at Query.formatError (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\dialects\mysql\query.js:256:16)
at Query.run (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\dialects\mysql\query.js:68:18)
at processTicksAndRejections (node:internal/process/task_queues:93:5)
at async C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\sequelize.js:619:16
at async MySQLQueryInterface.insert (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\dialects\abstract\query-interface.js:748:21)
at async model.save (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\model.js:3954:35)
at async Function.create (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\model.js:2207:12)
at async module.exports.createOne (C:\Users\semer\Desktop\testing skills\toDoBlog\server\controllers\userController.js:6:16) {
parent: Error: Table 'todoblog.users' doesn't exist
at Packet.asError (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\packets\packet.js:712:17)
at Prepare.execute (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\commands\command.js:28:26)
at Connection.handlePacket (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\connection.js:425:32)
at PacketParser.onPacket (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\connection.js:75:12)
at PacketParser.executeStart (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\packet_parser.js:75:16)
at Socket.<anonymous> (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\connection.js:82:25)
at Socket.emit (node:events:329:20)
at addChunk (node:internal/streams/readable:304:12)
at readableAddChunk (node:internal/streams/readable:279:9)
at Socket.Readable.push (node:internal/streams/readable:218:10) {
code: 'ER_NO_SUCH_TABLE',
errno: 1146,
sqlState: '42S02',
sqlMessage: "Table 'todoblog.users' doesn't exist",
sql: 'INSERT INTO `users` (`user_id`,`name`,`email`,`password`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?);',
parameters: [
'SEMER',
'semer',
'hash(info.password)',
'2021-03-04 16:57:41',
'2021-03-04 16:57:41'
]
},
original: Error: Table 'todoblog.users' doesn't exist
at Packet.asError (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\packets\packet.js:712:17)
at Prepare.execute (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\commands\command.js:28:26)
at Connection.handlePacket (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\connection.js:425:32)
at PacketParser.onPacket (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\connection.js:75:12)
at PacketParser.executeStart (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\packet_parser.js:75:16)
at Socket.<anonymous> (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\connection.js:82:25)
at Socket.emit (node:events:329:20)
at addChunk (node:internal/streams/readable:304:12)
at readableAddChunk (node:internal/streams/readable:279:9)
at Socket.Readable.push (node:internal/streams/readable:218:10) {
code: 'ER_NO_SUCH_TABLE',
errno: 1146,
sqlState: '42S02',
sqlMessage: "Table 'todoblog.users' doesn't exist",
sql: 'INSERT INTO `users` (`user_id`,`name`,`email`,`password`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?);',
parameters: [
'SEMER',
'semer',
'hash(info.password)',
'2021-03-04 16:57:41',
'2021-03-04 16:57:41'
]
},
sql: 'INSERT INTO `users` (`user_id`,`name`,`email`,`password`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?);',
parameters: [
'SEMER',
'semer',
'hash(info.password)',
'2021-03-04 16:57:41',
'2021-03-04 16:57:41'
]
}
[nodemon] app crashed - waiting for file changes before starting...

Related

the node server is braked after getting an error

I'm new in NodeJS I got this error ( this.$__.validationError = new ValidationError(this);)
I try to use try{..}catch(e){..} but it still the same problem inside post user but always the same
I'm confused what I should do
the error
C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\document.js:3125
this.$__.validationError = new ValidationError(this);
^
ValidationError: User validation failed: password: Path `password` is required.
at model.Document.invalidate (C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\document.js:3125:32)
at C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\document.js:2913:17
at C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\schematype.js:1349:9
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
errors: {
password: ValidatorError: Path `password` is required.
at validate (C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\schematype.js:1346:13) at SchemaString.SchemaType.doValidate (C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\schematype.js:1330:7)
at C:\Users\toshiba\Desktop\express project\node_modules\mongoose\lib\document.js:2905:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: {
validator: [Function (anonymous)],
message: 'Path `password` is required.',
type: 'required',
path: 'password',
value: undefined
},
kind: 'required',
path: 'password',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'User validation failed'
}
user schema
const mongoose = require('mongoose')
const joi = require('joi')
const User = mongoose.model('User', new mongoose.Schema({
fullname:{
type:String,
required:true,
minlength:3,
maxlength:44
},
email:{
type:String,
required:true,
unique:true,
minlength:3,
maxlength:255
},
password:{
type:String,
required:true,
minlength:3,
maxlength:1025
}
}))
const validateUser = (body , res)=>{
const schema = joi.object({
fullname:joi.string().min(3).max(44).required(),
email:joi.string().min(3).max(255).required().email(),
password:joi.string().min(8).max(255).required()
})
const {error} = schema.validate(body)
if(error){
return res.status(404).send(error.message)
}
}
module.exports = {User,validateUser}
user routes
const express = require('express')
const router = express.Router()
const {User , validateUser} = require('../model/user')
//add new user
router.post('/' , async(req,res)=>{
validateUser(req.body , res)
//add the new user
const user = new User({
fullname:req.body.fullname,
email:req.body.email,
password:req.body.password
})
await user.save()
res.send(user)
})
module.exports = router
index.js
const mongoose = require('mongoose')
const app = express()
//for devlopment envirement
if(app.get('env') === 'development'){
app.use(morgan('tiny'))
}
mongoose.set('strictQuery', false);
mongoose.connect("mongodb://localhost:27017/expDB", { useNewUrlParser: true })
.then(()=> console.log("connected to database"))
.catch((error)=>console.error("there is an error" + error))
//using the middlewares
app.use(helmet())
app.use(express.json())
app.use('/employees', employees)
app.use('/user' , user)
//running the server
const PORT = process.env.PORT || 3000
app.listen(PORT , ()=>{
console.log(`app ronning on PORT ${PORT}...`)
})
when I added try catch in post user I got this error
node:internal/errors:477
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:387:5)
at ServerResponse.setHeader (node:_http_outgoing:603:11)
at ServerResponse.header (C:\Users\toshiba\Desktop\express project\node_modules\express\lib\response.js:794:10)
at ServerResponse.send (C:\Users\toshiba\Desktop\express project\node_modules\express\lib\response.js:174:12)
at ServerResponse.json (C:\Users\toshiba\Desktop\express project\node_modules\express\lib\response.js:278:15)
at ServerResponse.send (C:\Users\toshiba\Desktop\express project\node_modules\express\lib\response.js:162:21)
at C:\Users\toshiba\Desktop\express project\routes\user.js:18:19
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
post req
//add new user
router.post('/' , async(req,res)=>{
try{
validateUser(req.body , res)
//add the new user
const user = new User({
fullname:req.body.fullname,
email:req.body.email,
password:req.body.password
})
await user.save()
res.send(user)
}catch(err){
res.status(404).send(err)
}
})

Can't use and connect to MongoDB

So, I am building a small URL shortener project with js, express, and MongoDB but, I got errors when I'm trying to run my local server and I can't connect to MongoDB!
This is my code:
const express = require('express')
const mongoose = require('mongoose')
const ShortUrl = require('./models/shortUrl')
const app = express();
mongoose.connect('mongodb://localhost/urlShortener', {
useNewUrlParser: true, useUnifiedTopology: true
})
app.set('view engine', 'ejs')
app.use(express.urlencoded({ extended: false}))
app.get('/', async (req, res) => {
const shortUrls = await ShortUrl.find()
res.render('index', { shortUrls: shortUrls })
});
app.post('/shortUrls', async (req, res) => {
await ShortUrl.create({ full: req.body.fullUrl })
res.redirect('/')
})
app.get('/:shortUrl', async (req, res) => {
const shortUrl = await ShortUrl.findOne({ short: req.params.shortUrl })
if (shortUrl == null) return res.sendStatus(404)
shortUrl.clicks++
shortUrl.save()
res.redirect(shortUrl.full)
})
app.listen(process.env.PORT || 5000);
And this is the full log:
[nodemon] 2.0.15
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\connection.js:807
const serverSelectionError = new ServerSelectionError();
^
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at NativeConnection.Connection.openUri (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\connection.js:807:32)
at C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\index.js:342:10
at C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\index.js:1176:10)
at Mongoose.connect (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\index.js:341:20)
at Object.<anonymous> (C:\Users\apsoltanian-pc\Documents\js\url-shortener\server.js:6:10)
at Module._compile (node:internal/modules/cjs/loader:1099:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 1096791,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongodb\lib\cmap\connect.js:381:20)
at Socket.<anonymous> (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongodb\lib\cmap\connect.js:301:22)
at Object.onceWrapper (node:events:642:26)
at Socket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
}
}
Node.js v17.7.2
[nodemon] app crashed - waiting for file changes before starting...
Thank u guys =)
I was trying to start the small URL-shortener project that I wrote in js, express, and MongoDB but, the problem is that I can't connect to my MongoDB database :(
I solved the problem, so, I replaced localhost with 127.0.0.1 in the connection string and now my problem is solved!
it is because of some ipv6 configurations...
Thank u :)

How do i fix inserting to database with Sequelize Node Express Mysql?

I am trying to create a simple registration form which i will then proceed to other CRUD operations new to node js
I have created the mysql database and done the modelling and connection with Sequelize also i have created my view with pug and i did console.log for the entries from my form and everything is fine till it gets to database insert
var express = require('express');
var router = express.Router();
var Sequelize = require("sequelize");
var db = require('../src/database/connection');
var User = require('../src/model/User');
router.get('/', function(req, res, next){
res.render('signup');
});
router.post('/register', function(req, res, next){
let { username, useremail, pass, re_pass } = req.body;
let errors = [];
//checking feilds
if( !username || !useremail || !pass || !re_pass)
{
errors.push({msg: 'Please no field should be left empty'});
}
//checking Password
if(pass !== re_pass)
{
errors.push({msg: 'Passwords Dont Match'});
}
//check Password Length
if(pass.length < 7)
{
errors.push({msg: 'Passwords should be more than 7 characters '})
}
//reload page with contents if error encountered
if(errors.length > 0)
{
res.render('signup', {
errors,
username,
useremail,
pass,
re_pass
});
} else{
console.log(req.body);
User.create({
username,
useremail,
pass,
}).then(user => res.redirect('/register')).catch(err => console.log(err));
}
});
module.exports = router;
This is the error i am getting. PLEASE HELP
{ SequelizeValidationError: notNull Violation: User.email cannot be null,
notNull Violation: User.password cannot be null
at Promise.all.then (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\sequelize\lib\instance-validator.js:74:15)
at tryCatcher (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\util.js:16:23)
at Promise._settlePromiseFromHandler (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:512:31)
at Promise._settlePromise (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:569:18)
at Promise._settlePromise0 (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:614:10)
at Promise._settlePromises (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:694:18)
at Promise._fulfill (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:638:18)
at PromiseArray._resolve (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise_array.js:126:19)
at PromiseArray._promiseFulfilled (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise_array.js:144:14)
at Promise._settlePromise (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:574:26)
at Promise._settlePromise0 (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:614:10)
at Promise._settlePromises (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\promise.js:694:18)
at _drainQueueStep (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\async.js:138:12)
at _drainQueue (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\async.js:131:9)
at Async._drainQueues (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\async.js:147:5)
at Immediate.Async.drainQueues [as _onImmediate] (C:\Users\ONLINEWIS-PROG-03\Documents\Node\waiyu\node_modules\bluebird\js\release\async.js:17:14)
at runCallback (timers.js:705:18)
at tryOnImmediate (timers.js:676:5)
at processImmediate (timers.js:658:5)
name: 'SequelizeValidationError',
errors:
[ ValidationErrorItem {
message: 'User.email cannot be null',
type: 'notNull Violation',
path: 'email',
value: null,
origin: 'CORE',
instance: [User],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: [] },
ValidationErrorItem {
message: 'User.password cannot be null',
type: 'notNull Violation',
path: 'password',
value: null,
origin: 'CORE',
instance: [User],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: [] } ] }
Seems like req.body is always empty
use body parser to put request body to req.body
const express = require('express'),
app = express(),
bodyParser = require('body-parser');
// support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));
Thanks to everyone that tried helping me solve this problem so my mistake was that i didnt point to the database rows in the create method so what i did was
User.create({
username: req.body.username,
email: req.body.useremail,
password: req.body.pass,
}).then(user => res.redirect('signup/register')).catch(err => console.log(err));
not
User.create({
username,
useremail,
pass,
}).then(user => res.redirect('/register')).catch(err => console.log(err));

JavaScript AWS Cognito Connection Problems "NetworkError"

I'm running into a strange problem with AWS Cognito. I'm able to create user accounts, however when I attempt to set the created user to a group it is
giving me a network timed out error.
Setup:
const AmazonCognitoIdentity = require('amazon-cognito-identity-js')
const AWS = require('aws-sdk')
const CognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider({
region: 'us-east-1 ', // 100% sure this is the correct region
apiVersion: '2016-04-18'
})
const UserPoolId = config.cognito.userPoolId
const ClientId = config.cognito.clientId
const userPool = new AmazonCognitoIdentity.CognitoUserPool({ UserPoolId, ClientId })
Creating account:
userPool.signUp(email, password, [ emailAttribute ], null, (err, data) => {
if(err) {
console.error(err)
return res.redirect('/signup')
}
CognitoIdentityServiceProvider.adminAddUserToGroup({
GroupName: 'TRIAL',
UserPoolId,
Username: email
}, (err, data) => {
if(err) {
console.error(err)
return res.redirect('/signup')
}
res.redirect('/dashboard')
})
})
The account gets made correctly, however when attempting to add the new account to a group I get this error:
{ Error: connect ETIMEDOUT 104.239.207.44:443
at Object._errnoException (util.js:1022:11)
at _exceptionWithHostPort (util.js:1044:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1198:14)
message: 'connect ETIMEDOUT 104.239.207.44:443',
code: 'NetworkingError',
errno: 'ETIMEDOUT',
syscall: 'connect',
address: '104.239.207.44',
port: 443,
region: 'us-east-1 ',
hostname: 'cognito-idp.us-east-1',
retryable: true,
time: 2018-06-20T14:01:49.029Z }
I find this very strange as I just was able to create an account successfully.
Any ideas on why this is happening?
Thanks

Trouble making nodejs mysql connection

I am trying to make a simple connection between my nodejs server and my mysql db (using Microsoft SQL server manager studio v14), below is my code and the error message appearing in my console window.
here is my code:
var express = require('express');
var app = express();
var sql = require("mssql");
app.get('/', function (req, res) {
// config for your database
var config = {
user: 'superadmin',
password: '***',
server: 'localhost',
database: 'XXX'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from Schools', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
The error I am getting looks like this:
Server is running..
tedious deprecated The default value for `options.encrypt` will change from `false` to `true`. Please pass `false` explicitly if you want to retain current behaviour. node_modules\mssql\lib\tedious.js:212:23
{ ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at Connection.tedious.once.err (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\tedious.js:216:17)
at Object.onceWrapper (events.js:275:13)
at Connection.emit (events.js:182:13)
at Connection.socketError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:1004:14)
at C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:869:25
at SequentialConnectionStrategy.connect (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:154:9)
at Socket.onError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:170:16)
at Socket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
code: 'ESOCKET',
originalError:
{ ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at ConnectionError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\errors.js:12:12)
at Connection.socketError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:1004:30)
at C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:869:25
at SequentialConnectionStrategy.connect (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:154:9)
at Socket.onError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:170:16)
at Socket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at process._tickCallback (internal/process/next_tick.js:174:19)
message: 'Failed to connect to localhost:1433 - Could not connect (sequence)',
code: 'ESOCKET' },
name: 'ConnectionError' }
{ ConnectionError: Connection is closed.
at Request._query (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\base.js:1299:37)
at Request._query (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\tedious.js:497:11)
at Request.query (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\base.js:1242:12)
at C:\Users\smr09\Desktop\Code\ou\db_test\test.js:24:17
at _poolCreate.then.catch.err (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\base.js:269:7)
at process._tickCallback (internal/process/next_tick.js:178:7) code: 'ECONNCLOSED', name: 'ConnectionError' }
I am rather new at this particularly with dealing with databases. Can someone explain what the error means?
Add this line to the config:
options: {
encrypt: false
}
It will finally look like:
var config = {
user: 'superadmin',
password: '***',
server: 'localhost',
database: 'XXX' ,
options: {
encrypt: false
}
};
try to put encrypt: false in your config{}, it will work.
your error:
ConnectionError: Failed to connect to localhost:1433 - Could not
connect (sequence)
My problem was resolved by adding port
var config = {
user: 'superadmin',
password: '***',
server: 'localhost',
database: 'XXX',
port: '',
};

Categories

Resources